如何从主机字节顺序的值转换为小端? [英] How do I convert a value from host byte order to little endian?

查看:147
本文介绍了如何从主机字节顺序的值转换为小端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简短值从主机字节序转换为小端。如果目标是大端,我可以使用htons()函数,但很可惜 - 这不是

I need to convert a short value from the host byte order to little endian. If the target was big endian, I could use the htons() function, but alas - it's not.

我想我可以这样做:

swap(htons(val))

但是,这有可能导致字节被换两次,渲染后的结果正确的,但给我的性能损失这是不是在我的情况好了。

But this could potentially cause the bytes to be swapped twice, rendering the result correct but giving me a performance penalty which is not alright in my case.

推荐答案

类似以下内容:

unsigned short swaps( unsigned short val)
{
    return ((val & 0xff) << 8) | ((val & 0xff00) >> 8);
}

/* host to little endian */

#define PLATFORM_IS_BIG_ENDIAN 1
#if PLATFORM_IS_LITTLE_ENDIAN
unsigned short htoles( unsigned short val)
{
    /* no-op on a little endian platform */
    return val;
}
#elif PLATFORM_IS_BIG_ENDIAN
unsigned short htoles( unsigned short val)
{
    /* need to swap bytes on a big endian platform */
    return swaps( val);
}
#else
unsigned short htoles( unsigned short val)
{
    /* the platform hasn't been properly configured for the */
    /* preprocessor to know if it's little or big endian    */

    /* use potentially less-performant, but always works option */

    return swaps( htons(val));
}
#endif

如果您有配置正确的系统(使得preprocessor知道是否达到了目标的ID小或大尾数),你得到 htoles的优化的版本()。否则,你得到潜在的非优化的版本,这取决于 htons()。在任何情况下,你会得到一些作品。

If you have a system that's properly configured (such that the preprocessor knows whether the target id little or big endian) you get an 'optimized' version of htoles(). Otherwise you get the potentially non-optimized version that depends on htons(). In any case, you get something that works.

没有什么太棘手,或多或少的便携性。

Nothing too tricky and more or less portable.

当然,你还可以通过您认为合适的与在线或宏执行这一改进优化可能性。

Of course, you can further improve the optimization possibilities by implementing this with inline or as macros as you see fit.

您可能想看看像手提开源线束(POSH)为实际的实现,它定义了各种编译器的字节顺序。请注意,让图书馆需要去虽然是伪认证页面(虽然你并不需要注册提供任何个人信息)的 http://hookatooka.com/poshlib/

You might want to look at something like the "Portable Open Source Harness (POSH)" for an actual implementation that defines the endianness for various compilers. Note, getting to the library requires going though a pseudo-authentication page (though you don't need to register to give any personal details): http://hookatooka.com/poshlib/

这篇关于如何从主机字节顺序的值转换为小端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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