大端和字节顺序小端支持 [英] Big Endian and Little Endian support for byte ordering

查看:334
本文介绍了大端和字节顺序小端支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要支持3硬件平台 - 视窗(小端)和嵌入式Linux(大和little endian)。我们的数据流是依赖它使用的机器上,并且该数据需要被分成位字段

We need to support 3 hardware platforms - Windows (little Endian) and Linux Embedded (big and little Endian). Our data stream is dependent on the machine it uses and the data needs to be broken into bit fields.

我想编写一个宏(如果可能)抽象掉的细节。在Linux上我可以使用 bswap_16 / bswap_32 / bswap_64 的小Endian转换。

I would like to write a single macro (if possible) to abstract away the detail. On Linux I can use bswap_16/bswap_32/bswap_64 for Little Endian conversions.

不过,我不能在我的Visual C ++包括找到。

However, I can't find this in my Visual C++ includes.

有一个通用的内置两个平台(Windows和Linux)?

Is there a generic built-in for both platforms (Windows and Linux)?

如果没有,那么我能在Visual C ++用做字节交换?(不是写我自己 - 希望一些机器进行了优化内置)

If not, then what can I use in Visual C++ to do byte swapping (other than writing it myself - hoping some machine optimized built-in)?

感谢。

推荐答案

在这两个平台都使用

(16位): htons() ntohs和()

(32位): htonl() ntohl()

缺少 htonll() ntohll()长长(64位)可以很容易地从这两个构建。请参见例如此实现。

The missing htonll() and ntohll() for long long (64bit) could easily be build from those two. See this implementation for example.

更新 - 0:

有关上述西门里氏挂钩的例子中提到了一个评论,它不一定有工作。这样做的原因是:编译器可能会使用的地方工会引入额外的字节。要解决此工会需要进行包装。后者可能会导致性能损失。

For the example linked above Simon Richter mentions in a comment, that it not necessarily has to work. The reason for this is: The compiler might introduce extra bytes somewhere in the unions used. To work around this the unions need to be packed. The latter might lead to performance loss.

所以这里的另一个故障安全的方法来构建 * LL 功能: http://stackoverflow.com/a/955980/694576

So here's another fail-safe approach to build the *ll functions: http://stackoverflow.com/a/955980/694576

更新 - 0.1:

从bames53的评论我倾向于断定上面链接不得与C ++中使用的第一个例子,但仅C。

From bames53' s comment I tend to conclude the 1st example linked above shall not be used with C++, but with C only.

更新1:

要实现后的功能的 *在Linux上这种方法可能LL 功能是最好的

To achieve the functionallity of the *ll functions on Linux this approach might be the ' best'.

这篇关于大端和字节顺序小端支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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