首页 > 解决方案 > 如何从 int 变量中提取字节(存储在 int 变量中的十六进制值)?

问题描述

我试图从存储在 int 变量中的十六进制值中提取 4 个字节。

我的想法是通过使用右移运算符(>>)将想要的字节“推”到末尾,然后使用带有 0xFF 值的 AND 运算符仅获得最后 8 位值。它适用于数值(例如 73),但不适用于值 af(例如 3f)。我尝试使用不同的 printf 格式,例如 %02x ,并且我还尝试将 AND 运算符的掩码更改为 0x000000FF。

int variable = 0x12cd34f4; 
char byte0, byte1, byte2, byte3; 

byte0 = (char)(variable & 0xFF);
byte1 = (char)((variable >> 8) & 0xFF);
byte2 = (char)((variable >> 16) & 0xFF);
byte3 = (char)((variable >> 24) & 0xFF);

printf("%x\n",byte0);// prints fffffff4 
printf("%x\n",byte1);// prints 34
printf("%x\n",byte2);//prints ffffffcd
printf("%x\n",byte3);//prints 12

我希望它为 byte0打印f4 ,为 byte1打印34 ,为 byte2 打印cd,为 byte3 打印12,但是 byte0 的实际输出是fffffff4和 byte2 ffffffcd。我不明白为什么要添加这些 F 值,以及如何摆脱它们。

标签: chexbitwise-operators

解决方案


char can be signed or unsigned, that is system dependent (and, maybe, as well depending on compiler options).

In your case, it is obviously signed. Values between 0x80 and 0xFF (and not only those starting from 0xA0!) have bit #7 set and are interpreted as signed value (e. g., 0xFF is -1, 0xF0 is -16, etc.).

When extending them to int (that's what happens when calling printf()), they are sign-extended (that's what the Fs come from) and thus retain their "interpreted value". printf(), however, is told to treat them as unsigned again, so the -16 is represented as 0xFFFFFFF0.

Either use unsigned char resp. uint8_t or add & 0xFF when calling printf().


推荐阅读