gpt4 book ai didi

c++ - unsigned char 数组到 unsigned int 通过 memcpy 返回到 unsigned char 数组被反转

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:12:31 28 4
gpt4 key购买 nike

这不是跨平台代码...所有内容都在同一平台上执行(即字节序是相同的......小字节序)。

我有这个代码:


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

我希望 buff 的输出是“test”(由于缺少“/0”而带有垃圾尾随字符),但输出却是“tset”。显然,更改我要移动的字符的顺序(3、2、1、0 而不是 0、1、2、3)可以解决问题,但我不明白这个问题。 memcpy 是否没有按我预期的方式运行?

谢谢。

最佳答案

这是因为你的CPU是little-endian .在内存中,数组存储为:

      +----+----+----+----+
array | 74 | 65 | 73 | 74 |
+----+----+----+----+

这用增加字节地址到右边来表示。但是,整数存储在内存中时,最低 有效字节位于左侧:

    +----+----+----+----+
out | 74 | 73 | 65 | 74 |
+----+----+----+----+

这恰好表示整数 0x74657374。使用 memcpy() 将其复制到 buff 中会反转原始 array 中的字节。

关于c++ - unsigned char 数组到 unsigned int 通过 memcpy 返回到 unsigned char 数组被反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1584296/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com