我正在尝试将 4 个十六进制字节连接在一起,但遇到了一些麻烦。
我有一个 32 位数字,表示为 4 个十六进制字节 (x
)。我还有另一个 4 位数字,我将 2 的补码作为 (twos_complement
),然后将其转换为十六进制表示 (ne
)。然后我想将单个字节 (ne
) 作为原始 32 位数字 (x
) 的第三个字节。这是我到目前为止所拥有的:
unsigned replace_byte(unsigned x, unsigned char b) {
unsigned new;
unsigned int twos_complement;
twos_complement = (~b) +1;
unsigned int ne = (twos_complement & 0xff);
unsigned int one = (x >> 24) & 0xff;
unsigned int two = (x >> 16) & 0xff;
unsigned int three = (x >> 8) & 0xff;
unsigned int four = x & 0xff;
printf("one 0x%x, two 0x%x, three 0x%x, four 0x%x\n",one, two, three, four);
new = (one<<24) | (two<<16) | (ne) | (four) ;
printf("new 0x%x", new);}
当我输入 11123243336 作为 i
并输入 3 作为 b
时,我得到的十六进制值为 i = 0x96ff3948
和 b = 0xfffffffd
。当我运行这个程序时,当我期待 0x96fffd48
时,我得到 new
为 0x96ff00fd
。
任何帮助表示赞赏!
最佳答案
我不太清楚你想要实现什么,但根据你的期望,我的猜测是你只需要移动 ne
8 位,所以:
new = (one<<24) | (two<<16) | (ne<<8) | (four) ;
关于在C中连接十六进制字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54318092/