天天看点

c语言中int转char数组,将int转换为4字节的char数组(C)

可移植的方式(确保你得到0x00 0x00 0x00 0xaf无处不在)是使用shift:

unsigned char bytes[4];

unsigned long n = 175;

bytes[0] = (n >> 24) & 0xFF;

bytes[1] = (n >> 16) & 0xFF;

bytes[2] = (n >> 8) & 0xFF;

bytes[3] = n & 0xFF;

使用union和memcpy()的方法将在不同的机器上获得不同的结果。

你所遇到的问题是与打印而不是转换。我假设你使用char而不是unsigned char,并且你正在使用这样的行打印它:

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);

当任何比int更窄的类型被传递给printf时,它们被提升为int(或unsigned int,如果int不能容纳原始类型的所有值)。如果char在您的平台上签名,那么0xff可能不适合该类型的范围,并且它被设置为-1(在2s补充机器上具有表示0xff)。

-1被提升为一个int,并在你的机器上有一个int的表示0xffffffff,这就是你看到的。

您的解决方案是要么实际使用unsigned char,要么转换为printf语句中的unsigned char:

printf("%x %x %x %x\n", (unsigned char)bytes[0],

(unsigned char)bytes[1],

(unsigned char)bytes[2],

(unsigned char)bytes[3]);