如何检查存储在地址中的各个字节的情况?

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; 

}

例如,我有这段代码显示输出:

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;
    }