更改字节序的最快方法 [英] Quickest way to change endianness
问题描述
反转16位和32位整数的字节序的最快方法是什么。我通常会做类似的事情(此编码是在C ++中的Visual Studio中完成的):
What is the quickest way to reverse the endianness of a 16 bit and 32 bit integer. I usually do something like (this coding was done in Visual Studio in C++):
union bytes4
{
__int32 value;
char ch[4];
};
union bytes2
{
__int16 value;
char ch[2];
};
__int16 changeEndianness16(__int16 val)
{
bytes2 temp;
temp.value=val;
char x= temp.ch[0];
temp.ch[0]=temp.ch[1];
temp.ch[1]=x;
return temp.value;
}
__int32 changeEndianness32(__int32 val)
{
bytes4 temp;
temp.value=val;
char x;
x= temp.ch[0];
temp.ch[0]=temp.ch[1];
temp.ch[1]=x;
x= temp.ch[2];
temp.ch[2]=temp.ch[3];
temp.ch[3]=x;
return temp.value;
}
有没有更快的方法,我不必进行很多计算?
Is there any faster way to do the same, in which I don't have to do so many calculations?
推荐答案
为什么不使用内置的 swab
函数,它可能比您的代码更好地优化了?
Why aren't you using the built-in swab
function, which is likely optimized better than your code?
除此之外,通常的移位操作应该是快速开始,并且使用如此广泛,它们可能会被优化程序识别并被更好的代码取代。
Beyond that, the usual bit-shift operations should be fast to begin with, and are so widely used they may be recognized by the optimizer and replaced by even better code.
因为其他答案都有严重的错误,所以我将发布更好的实现:
Because other answers have serious bugs, I'll post a better implementation:
int16_t changeEndianness16(int16_t val)
{
return (val << 8) | // left-shift always fills with zeros
((val >> 8) & 0x00ff); // right-shift sign-extends, so force to zero
}
我测试过的编译器为此代码生成 rolw
,我认为稍长的序列(就指令数而言)实际上更快。基准会很有趣。
None of the compilers I tested generate rolw
for this code, I think a slightly longer sequence (in terms of instruction count) is actually faster. Benchmarks would be interesting.
对于32位,有一些可能的操作命令:
For 32-bit, there are a few possible orders for the operations:
//version 1
int32_t changeEndianness32(int32_t val)
{
return (val << 24) |
((val << 8) & 0x00ff0000) |
((val >> 8) & 0x0000ff00) |
((val >> 24) & 0x000000ff);
}
//version 2, one less OR, but has data dependencies
int32_t changeEndianness32(int32_t val)
{
int32_t tmp = (val << 16) |
((val >> 16) & 0x00ffff);
return ((tmp >> 8) & 0x00ff00ff) | ((tmp & 0x00ff00ff) << 8);
}
这篇关于更改字节序的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!