c - 了解两种字节顺序

标签 c endianness

谁能帮我理解下面的文字:

Both-byte orders

A numerical value represented by the hexadecimal representation (st uv wx yz) shall be recorded in an eight-byte field as (yz wx uv st st uv wx yz).

NOTE: For example, the decimal number 305419896 has (12 34 56 78) as its hexadecimal representation and is recorded as (78 56 34 12 12 34 56 78).

这对于读取值意味着什么?我是简单地将 32 位作为 uint32 获取,仅此而已,还是我需要转换某些内容才能获得正确的值?还是我只从 8 字节字段中提取 4 字节以获得值?

编辑: 这在这样的 union 中行得通吗?

union test
{
   uint64 fullValue;
   uint8  FirstFourBytes[4];
   uint8  SecondFourBytes[4];
}

然后我访问 SecondFourBytes 数组以获取正确的值。

最佳答案

字节顺序是指组成较大数据类型(例如 32 位整数)的各个字节在内存中存储的顺序。

传统上,一个 32 位整数写在 Little Endian or Big Endian 中内存中的字节顺序,占用 4 个字节(32 位),但在您的情况下,协议(protocol)规定整数以 Little Endian 和 Big Endian 顺序依次存储,将存储所需的空间加倍至 64 位.

读取时,您必须考虑到该值使用 8 个字节,您可以读取前 4 个字节(小端)或后 4 个字节(大端),具体取决于哪种字节序(字节顺序)您的平台使用。

编写时,您必须序列化两个版本,首先写出小端表示,然后是大端表示。

更新 2

您修改后的 union 仍然无法工作,因为您现在正试图在 uint64 大概是 64 位数据类型和两个其他数组之间创建一个 union ,每个数组占用 4 个字节(32 位)。

// this is not right
union test
{
   uint64 fullValue;
   uint8  FirstFourBytes[4];   // this points to the first 4 bytes
   uint8  SecondFourBytes[4];  // .. despite name, this also points to the first 4 bytes
}

但是,您可以使用这样的 union :

union test
{
   uint64 fullValue;              // although this is probably useless to you
   struct Raw
   {
      uint8  LittleEndianBytes[4];
      uint8  BigEndianBytes[4];
   };
}

关于c - 了解两种字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19279017/

相关文章:

C 指针 "type ** name"与 "type * name[]"作为参数

c - MPI:广播一个 long long int

c# - 写入二进制多字节数组消息(大端)(.Net C#)

c - 我怎样才能正确移动这个 uint64_t 号码?

c++ - 如何通过屏幕右侧的输出而不是 C 中通常的左侧进行打印?

c - 做while循环,添加多个条件

c - c中不同模块的lua_pushlightuserdata元表的行为

xor - IPv6 的 STUN 服务器 xoring

c++ - 大端和小端的程序

objective-c - CAFAudioDescription 成员类型和字节顺序