你怎么写(可移植的)反网络字节顺序? [英] How do you write (portably) reverse network byte order?
问题描述
的背景的
在设计的二进制文件格式时,它一般建议写在网络字节顺序整数。为此,有像 htonhl宏()
。但是,对于一个格式,如WAV,其实小尾数格式。
When designing binary file formats, it's generally recommended to write integers in network byte order. For that, there are macros like htonhl()
. But for a format such as WAV, actually the little endian format is used.
的问题的
你怎么可移植性写小尾数值,无论在CPU的code运行在一个big endian还是little endian的架构(想法:可以在标准的宏 ntohl()
和 htonl()
用反向不知何故?还是应该由code只是测试运行时,如果它是一点点或大端CPU上运行,并选择适当的code路径?)
How do you portably write little endian values, regardless of if the CPU your code runs on is a big endian or little endian architecture? (Ideas: can the standard macros ntohl()
and htonl()
be used "in reverse" somehow? Or should the code just test runtime if it's running on a little or big endian CPU and choose the appropriate code path?)
<子>所以,问题是不是真正的文件格式,文件格式只是一个例子。它可以是任何种类的系列化的其中需要上线小端,如(异端)网络协议子>
推荐答案
C处已经提供了对主机的字节序的抽象:在的若干 的&匕首;或 INT 的匕首和。
C already provides an abstraction over the host's endianness: the number† or int†.
生产在一个给定的字节顺序输出能够方便地通过不巧言令色完成
Producing output in a given endianness can be done portably by not trying to be clever: simply interpret the numbers as numbers and use bit shifts to extract each byte:
uint32_t value;
uint8_t lolo = (value >> 0) & 0xFF;
uint8_t lohi = (value >> 8) & 0xFF;
uint8_t hilo = (value >> 16) & 0xFF;
uint8_t hihi = (value >> 24) & 0xFF;
然后你只写在你希望的任何顺序字节。
Then you just write the bytes in whatever order you desire.
当你正在服用的字节序列与一些字节顺序输入,可以通过再次与位操作数构造重建他们在主机的字节序:
When you are taking byte sequences with some endianness as input, you can reconstruct them in the host's endianness by again constructing numbers with bit operations:
uint32_t value = (hihi << 24)
| (hilo << 16)
| (lohi << 8)
| (lolo << 0);
&匕首;只有数字为字节顺序的重新presentations有字节顺序;数字(即数量)没有。
† Only the representations of numbers as byte sequences have endianness; numbers (i.e. quantities) don't.
这篇关于你怎么写(可移植的)反网络字节顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!