我有一个使用一个联合到一个64位整数,其相应的字节数组之间的转换如下简单的程序:C/C++转换一个64位整数为char阵列
union u
{
uint64_t ui;
char c[sizeof(uint64_t)];
};
int main(int argc, char *argv[])
{
u test;
test.ui = 0xabcdefLL;
for(unsigned int idx = 0; idx < sizeof(uint64_t); idx++)
{
cout << "test.c[" << idx << "] = 0x" << hex << +test.c[idx] << endl;
}
return 0;
}
我期望作为输出什么是:
test.c[0] = 0xef
test.c[1] = 0xcd
test.c[2] = 0xab
test.c[3] = 0x89
test.c[4] = 0x67
test.c[5] = 0x45
test.c[6] = 0x23
test.c[7] = 0x1
但我实际上得到的是:
test.c[0] = 0xffffffef
test.c[1] = 0xffffffcd
test.c[2] = 0xffffffab
test.c[3] = 0xffffff89
test.c[4] = 0x67
test.c[5] = 0x45
test.c[6] = 0x23
test.c[7] = 0x1
我与GCC看到了这个在Ubuntu 14.04 LTS。
我一直在试图让我的头在这一段时间了。为什么字符数组的前4个元素显示为32位整数,并且0xffffff预置于它们?为什么只有前4个,为什么不是全部?有趣的是,当我使用数组写入流(这是整个事物的原始目的)时,写入了正确的值。但是通过char比较char数组显然会导致问题,因为前4个字符不等于0xef,0xcd等等。
转换为'(char *)'然后读取4个字节...? – SteJ
没有变化。此外,我总是可以用0x000000ff掩码char来获得期望的值。我只是对这种行为背后的原因感兴趣。 – tickferno
显然你的实现已经签署了字符。正常整数升级将签名扩展。 – ewd