#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;
}
例如,我在这里有这个代码显示输出:
Byte 0 = 33
Byte 1 = 67
Byte 2 = 101
Byte 3 = 135
如何检查条件以查看该值是否存储在地址中?
你的代码一次加载一个字节到byte
,它不是一个指针,所以你不能索引它。做
unsigned char *bytePtr = ((unsigned char *)&x);
for (size_t i = 0; i < sizeof(x); ++i) {
printf("Byte %d = %u\n", i, bytePtr[i]);
}
现在你可以使用bytePtr来做你的测试功能
你的byte
将保持最后的价值。如果要存储所有需要数组的值。考虑下面的例子。
#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;
}