我知道要获取变量类型使用的字节数,例如可以使用 sizeof(int)
。当您存储具有该变量类型的数字时,您如何获得所使用的各个字节的值? (即 int x = 125
。)
最佳答案
您必须知道每个“字节”中的位数(通常为 8)。然后,您可以通过将 int 与适当的掩码进行 AND 运算来依次提取每个字节。假设一个 int 是 32 位的,那么从 the_int 中取出 4 个字节:
int a = (the_int >> 24) & 0xff; // high-order (leftmost) byte: bits 24-31
int b = (the_int >> 16) & 0xff; // next byte, counting from left: bits 16-23
int c = (the_int >> 8) & 0xff; // next byte, bits 8-15
int d = the_int & 0xff; // low-order byte: bits 0-7
就是这样:每个字节都是 a、b、c 和 d 的低 8 位。
关于c - 如何获取变量的各个字节的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8680220/