Reputation: 11
#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?
Upvotes: 0
Views: 141
Reputation: 50180
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
Upvotes: 2
Reputation: 12732
Your byte
will hold last value. If you want to store all the values you need array.
Consider below example.
#include <stdio.h>
int main(){
int x = 2271560481; // 0x87654321
size_t i =0;
unsigned char byte[sizeof x];
for (i = 0; i < sizeof(x); ++i) {
byte[i] = *((unsigned char *)&x + i);
printf("Byte %d = %u\n", i, (unsigned)byte[i]);
}
if (byte[0] == 33 && byte[1] == 67 && byte[2] == 101 && byte[3] == 135)
{
return 1;
}
return 0;
}
Upvotes: 0