我知道要获取变量类型使用的字节数,您可以使用 sizeof(int)
。当您存储具有该变量类型的数字时,如何获取所使用的各个字节的值? (即int x = 125
。)
最佳答案
您必须知道每个“字节”中的位数(通常为 8)。然后,您可以通过将 int 与适当的掩码进行“与”运算来依次提取每个字节。假设一个 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/59246609/