我在移位操作上迷失了方向,我试图在32位int上反转字节顺序,我设法在网上查找的内容我到现在还很远,但似乎找不到为什么它不起作用
int32_t swapped = 0; // Assign num to the tmp
for(int i = 0; i < 32; i++)
{
swapped |= num & 1; // putting the set bits of num
swapped >>= 1; //shift the swapped Right side
num <<= 1; //shift the swapped left side
}
我正在这样打印
num = swapped;
for (size_t i = 0; i < 32; i++)
{
printf("%d",(num >> i));
}
您的代码看起来像它试图交换位,和非字节。如果要交换字节,则“ complete”方法为:
int32_t swapped = ((num >> 24) & 0x000000FF) |
((num >> 8) & 0x0000FF00) |
((num << 8) & 0x00FF0000) |
((num << 24) & 0xFF000000);
我说'完成',因为最后一个按位与可以省略,而第一个按位与可以省略如果num是无符号的。
如果要交换32位数字中的[bits] >>,则循环可能最大为16(如果为32,则前16个步骤将交换位,接下来的16个步骤将交换位他们又回来了)。
int32_t swapped = 0; for(int i = 0; i < 16; ++i) { // the masks for the two bits (hi and lo) we will be swapping // shift a '1' to the correct bit location based on the index 'i' uint32_t hi_mask = 1 << (31 - i); uint32_t lo_mask = 1 << i; // use bitwise and to mask out the original bits in the number uint32_t hi_bit = num & hi_mask; uint32_t lo_bit = num & lo_mask; // shift the bits so they switch places uint32_t new_lo_bit = hi_bit >> (31 - i); uint32_t new_hi_bit = lo_bit << (31 - i); // use bitwise-or to combine back into an int swapped |= new_lo_bit; swapped |= new_hi_bit; }
为提高可读性而编写的代码-有更快的方法来反转32位数字中的位。至于打印:
for (size_t i = 0; i < 32; i++)
{
bool bit = (num >> (31 - i)) & 0x1;
printf(bit ? "1" : "0");
}