如何检查存储在地址中的单个字节的条件?

问题描述 投票:0回答:2
#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

如何检查条件以查看该值是否存储在地址中?

c system memory-address
2个回答
2
投票

你的代码一次加载一个字节到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来做你的测试功能


0
投票

你的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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.