如何在 C++ 中的 big-endian 和 little-endian 值之间进行转换? [英] How do I convert between big-endian and little-endian values in C++?
问题描述
我如何在 C++ 中的 big-endian 和 little-endian 值之间进行转换?
How do I convert between big-endian and little-endian values in C++?
为清楚起见,我必须将二进制数据(双精度浮点值以及 32 位和 64 位整数)从一种 CPU 架构转换为另一种架构.这不涉及网络,所以 ntoh() 和类似的函数在这里不起作用.
For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.
注意:我接受的答案直接适用于我的目标编译器(这就是我选择它的原因).但是,这里还有其他非常好的、更便携的答案.
Note: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here.
推荐答案
如果您使用的是 Visual C++,请执行以下操作: 您包含 intrin.h 并调用以下函数:
If you're using Visual C++ do the following: You include intrin.h and call the following functions:
对于 16 位数字:
unsigned short _byteswap_ushort(unsigned short value);
对于 32 位数字:
unsigned long _byteswap_ulong(unsigned long value);
对于 64 位数字:
unsigned __int64 _byteswap_uint64(unsigned __int64 value);
8 位数字(字符)不需要转换.
8 bit numbers (chars) don't need to be converted.
此外,这些仅针对无符号值定义,它们也适用于有符号整数.
Also these are only defined for unsigned values they work for signed integers as well.
对于浮点数和双精度数,对于普通整数来说更困难,因为这些可能或不在主机字节顺序中.您可以在大端机器上获得小端浮点数,反之亦然.
For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa.
其他编译器也有类似的内在函数.
Other compilers have similar intrinsics as well.
例如在GCC中,您可以直接调用一些此处记录的内置函数:
In GCC for example you can directly call some builtins as documented here:
uint32_t __builtin_bswap32 (uint32_t x)
uint64_t __builtin_bswap64 (uint64_t x)
(无需包含某些内容).Afaik bits.h 也以非以 gcc 为中心的方式声明了相同的函数.
(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.
16 位交换只是位旋转.
16 bit swap it's just a bit-rotate.
调用内部函数而不是自己滚动可以为您提供最佳性能和代码密度顺便说一句..
Calling the intrinsics instead of rolling your own gives you the best performance and code density btw..
这篇关于如何在 C++ 中的 big-endian 和 little-endian 值之间进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!