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

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

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

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

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

 Byte 0 = 25 // 0x19 Byte 1 = 238 // 0xEE Byte 2 = 191 // 0xBF Byte 3 = 0 // 0x00 

您必须知道每个“字节”中的位数(通常为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位。

如果您想获取该信息,请说:

 int value = -278; 

(我选择了这个值因为它对125来说不是很有趣 – 最低有效字节是125而其他字节都是0!)

您首先需要一个指向该值的指针:

 int* pointer = &value; 

您现在可以将其强制转换为只有一个字节的’char’指针,并通过索引获取单个字节。

 for (int i = 0; i < sizeof(value); i++) { char thisbyte = *( ((char*) pointer) + i ); // do whatever processing you want. } 

请注意,int和其他数据类型的字节顺序取决于您的系统 - 查找'big-endian'与'little-endian'。

您可以使用union但请记住,字节顺序与处理器有关,称为Endianness http://en.wikipedia.org/wiki/Endianness

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

这应该工作:

 int x = 125; unsigned char *bytes = (unsigned char *) (&x); unsigned char byte0 = bytes[0]; unsigned char byte1 = bytes[1]; ... unsigned char byteN = bytes[sizeof(int) - 1]; 

但请注意,整数的字节顺序取决于平台。