小编biz*_*ack的帖子

通过memcpy将unsigned char数组转换为unsigned int返回unsigned char数组是相反的

这不是跨平台代码......一切都在同一平台上执行(即endianess是相同的..小端).

我有这个代码:


    unsigned char array[4] = {'t', 'e', 's', 't'};
unsigned int out = ((array[0]<<24)|(array[1]<<16)|(array[2]<<8)|(array[3])); std::cout << out << std::endl;
unsigned char buff[4]; memcpy(buff, &out, sizeof(unsigned int));
std::cout << buff << std::endl;

我希望buff的输出是"test"(由于缺少'/ 0'而带有垃圾尾随字符),而输出是"tset".显然改变我正在移动的字符顺序(3,2,1,0而不是0,1,2,3)解决了问题,但我不明白这个问题.memcpy不按我期望的方式行事吗?

谢谢.

c c++

4
推荐指数
1
解决办法
4294
查看次数

标签 统计

c ×1

c++ ×1