反转半字节

问题描述 投票:2回答:2

所以我遇到了一个有关“通过反转小数点来建立新数字的问题”。练习看起来像这样:写一个给定无符号的一种)退货以半字节顺序排列的值

我以为32位无符号的所有8个半字节应按相反的顺序放置。因此,以数字24为例,即00000000000000000000000000011000。=>反向应为:10000001000000000000000000000000。

#include <stdio.h>

unsigned getNibble(unsigned n,unsigned p){

unsigned mask = 0xFu;
unsigned nibble = 0;

nibble = (n&(mask<<p))>>p;

return nibble;

}


unsigned swapNibbles(unsigned n){
unsigned new = 0;
unsigned nibble;
for(unsigned i=0;i<(sizeof(n)*8);i=i+4){
    nibble = getNibble(n,i);
    new = (new<<i) + nibble;
}

return new;
}


int main(void) {

printf("0x%x",swapNibbles(24));

return 0;
}

我尝试调试它,直到进行到一分为止。在向右移动的其中之一处,它将“新”变量转换为0。

c bitwise-operators
2个回答
2
投票

此声明

new = (new << i) + nibble;

是错误的。应该有

new = (new << 4) + nibble;

1
投票

一种并行工作的方法:

uint32_t n = ...;

// Swap the nibbles of each byte.
n = (n & 0x0F0F0F0F ) << 4
  | (n & 0xF0F0F0F0 ) >> 4;

// Swap the bytes of each byte pair.
n = ( n & 0x00FF00FF ) << 8
  | ( n & 0xFF00FF00 ) >> 8;

// Swap the byte pairs.
n = ( n & 0x0000FFFF ) << 16
  | ( n & 0xFFFF0000 ) >> 16;

并行执行工作大大减少了操作数量。

          OP's       This     
          Approach   Approach 
--------  ---------  ---------
Shifts     24 /  48    6 /   8    32 bits / 64 bits
Ands        8 /  16    6 /   8
Ors*        8 /  16    3 /   4
Assigns     8 /  16    3 /   4
Adds        8 /  16    0 /   0
Compares    8 /  16    0 /   0
--------  ---------  ---------
          O(N)      O(log(N))

* Addition was used as "or" in your solution.
© www.soinside.com 2019 - 2024. All rights reserved.