我试图交换16位值的前8位和后8位。例如,00000001 11001100变为11001100 00000001;好吧,我不知道如何实现它。我尝试了不同的方法,但它不起作用....任何帮助将不胜感激。对不起,这个问题很简单。我刚开始学习点东西。谢谢你。我有一个功能:
unsigned short swap_bytes(unsigned short x) {
}
答案 0 :(得分:2)
unsigned short swap_bytes(unsigned short x) {
unsigned short result;
result = (x >> 8) | (x << 8);
return result;
}
瓦尔特
答案 1 :(得分:2)
假设该值恰好是16位。
unsigned short swap_bytes(unsigned short x)
{
unsigned short bitmask = 0x00FF;
unsigned short temp = x & bitmask;
x = x >> 8;
temp = temp << 8;
x = x | temp;
return x;
}
工作原理:
答案 2 :(得分:0)
#include <bitset>
using namespace std;
int main()
{
typedef union{
unsigned char arr[2];
short s;
}SwapBit;
SwapBit sb;
sb.s = 100;
cout<<bitset<16>(sb.s)<<endl;
std::swap(sb.arr[0], sb.arr[1]);
cout<<bitset<16>(sb.s)<<endl;
}
结果是:
0000000001100100
0110010000000000