如何在C ++中的big-endian和little-endian值之间进行转换? [英] How do I convert between big-endian and little-endian values in C++?

查看:4019
本文介绍了如何在C ++中的big-endian和little-endian值之间进行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中的big-endian和little-endian值之间进行转换?



编辑:为了清楚起见,我必须翻译二进制数据点值和32位和64位整数)从一个CPU体系结构到另一个。这不涉及网络,所以ntoh()和类似的功能不会在这里工作。



编辑#2:我接受的答案直接应用于编译器我targetting(这就是为什么我选择它)。

解决方案

如果您使用 Visual C ++ 执行以下操作:您包括intrin.h并调用以下函数:



对于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位数字(字符)不需要转换。

$ b $


$ b

对于浮点数和双精度,它比使用纯整数更困难因为这些可能或不可能在主机中按字节顺序。



其他编译器也有类似的内在函数。



GCC 中,您可以直接呼叫:

 code> int32_t __builtin_bswap32(int32_t x)
int64_t __builtin_bswap64(int64_t x)

(不需要包括东西)。 Afaik bits.h以非gcc为中心的方式声明相同的函数。



16位交换它只是一个位旋转。



调用内在函数而不是滚动你自己的函数给你最好的性能和代码密度btw ..


How do I convert between big-endian and little-endian values in C++?

EDIT: 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.

EDIT #2: The answer I accepted applies directly to compilers I'm targetting (which is why I chose it). However, there are other very good, more portable answers here.

解决方案

If you're using Visual C++ do the following: You include intrin.h and call the following functions:

For 16 bit numbers:

unsigned short _byteswap_ushort(unsigned short value);

For 32 bit numbers:

unsigned long _byteswap_ulong(unsigned long value);

For 64 bit numbers:

unsigned __int64 _byteswap_uint64(unsigned __int64 value);

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.

In GCC for example you can directly call:

int32_t __builtin_bswap32 (int32_t x)
int64_t __builtin_bswap64 (int64_t x)

(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.

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屋!

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