如何获取变量的单个字节的值?

Tob*_*bey 9 c byte

我知道要获取变量类型使用的字节数,sizeof(int)例如.当您使用该变量类型存储数字时,如何获得所使用的单个字节的值?(即int x = 125)

Pet*_*son 18

您必须知道每个"字节"中的位数(通常为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
Run Code Online (Sandbox Code Playgroud)

你有它:每个字节都在a,b,c和d的低位8位.

  • 如果a,b等的类型是unsigned char会是一个更好的例子。在这种情况下,如果变量大小合适,则编译器可以将变量分配到保存the_int的同一处理器寄存器中。 (2认同)
  • +1这个答案是最正确的.所有其他都依赖于endian.@dip它在许多平台上都不是处理器密集型的,无论如何,编译器会将其转换为幕后最佳实现***. (2认同)

小智 15

您可以使用一些指针算法来获取字节:

int x = 12578329; // 0xBFEE19
for (size_t i = 0; i < sizeof(x); ++i) {
  // Convert to unsigned char* because a char is 1 byte in size.
  // That is guaranteed by the standard.
  // Note that is it NOT required to be 8 bits in size.
  unsigned char byte = *((unsigned char *)&x + i);
  printf("Byte %d = %u\n", i, (unsigned)byte);
}
Run Code Online (Sandbox Code Playgroud)

在我的机器上(Intel x86-64),输出为:

Byte 0 = 25  // 0x19
Byte 1 = 238 // 0xEE
Byte 2 = 191 // 0xBF
Byte 3 = 0 // 0x00
Run Code Online (Sandbox Code Playgroud)


Dip*_*tch 5

您可以使用 aunion但请记住,字节顺序取决于处理器,称为 Endianness http://en.wikipedia.org/wiki/Endianness

#include <stdio.h>
#include <stdint.h>

union my_int {
   int val;
   uint8_t bytes[sizeof(int)];
};

int main(int argc, char** argv) {
   union my_int mi;
   int idx;

   mi.val = 128;

   for (idx = 0; idx < sizeof(int); idx++)
        printf("byte %d = %hhu\n", idx, mi.bytes[idx]);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)