将int强制转换为字节数组时的C ++字节顺序 [英] C++ byte order when casting int to byte array

查看:58
本文介绍了将int强制转换为字节数组时的C ++字节顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我的平台是低端字节序,我假设将一个四字节整数值1表示为 0x00 0x00 0x00 0x01 .这样,有人可以向我解释为什么以下断言失败了吗……

Given that my platform is little endian, I assumed that a four-byte integer value of 1 would be represented as 0x00, 0x00, 0x00, 0x01 when expressed as a byte array. With that, could someone explain to me why the following assertion fails ...

int val{1};
auto bytes = reinterpret_cast<char*>(&val);
assert(bytes[sizeof(int) - 1] == 0x01);

...但是以下断言成功了...

... but the following assertion succeeds ...

assert(bytes[0] == 0x01);

在强制转换为 char * 之后,字节似乎被反转了.我对字节序的假设是错误的吗?编译器(c)或语言是否抽象了字节序?发生了什么事?

After the cast to char*, the bytes appear to be reversed. Are my assumptions about endianness wrong? Is the compiler (clang) or language abstracting away the endianness? What's going on?

推荐答案

您的假设是相反的.在little endian中,32位整数值1以十六进制表示为 0x00000001 ,但以字节表示为 0x01 0x00 0x00 0x00 .

Your assumption is reversed. In little endian, a 32bit integer value of 1 is represented in hex as 0x00000001, but is represented in bytes as 0x01 0x00 0x00 0x00.

这篇关于将int强制转换为字节数组时的C ++字节顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆