Search code examples
csystemmemory-address

How to check the condition of individual bytes stored in an address?


#include <stdio.h>

int main(){

int x = 2271560481; // 0x87654321

for (size_t i = 0; i < sizeof(x); ++i) {

unsigned char byte = *((unsigned char *)&x + i);


printf("Byte %d = %u\n", i, (unsigned)byte);
}


return 0; 

}

For example I have this code right here displaying an output of :

Byte 0 = 33
Byte 1 = 67
Byte 2 = 101
Byte 3 = 135

How do I check the condition to see if the value is stored in the address?


Solution

  • Your code is loading one byte at a time into byte , its not a pointer so you cannot index off it. Do

    unsigned char *bytePtr = ((unsigned char *)&x);
    
    for (size_t i = 0; i < sizeof(x); ++i) {
    printf("Byte %d = %u\n", i, bytePtr[i]);
    }
    

    now you can do your test function using bytePtr