c反向二进制 [英] C reverse binary

查看:375
本文介绍了c反向二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
   c反向的无符号整数


我怎样才能扭转二进制数只能用二元操作?

例如:

  11100000  - > 00000111
00110100 - > 00101100
00111111 - > 11111100


解决方案

有关这样的事情,我建议你看一看的真棒页的Bit摆弄黑客

下面是从该页面只花了一个例子的解决方案:


  

反转一个字节中的位和3运算(64位乘法和
  模数师)

  unsigned char型B: //扭转这种(8位)字节
B =(B * 0x0202020202ULL&安培; 0x010884422010ULL)%1023;


和在评论中指出,这里有另一个选择:


  

反向并联N位数量在5 * LG电子(N)操作

 无符号整型伏; // 32位字反转位顺序//交换奇数和偶数位
V =((V>→1)及0x55555555)| ((V&放大器; 0x55555555)所述;&。1);
//交换连续对
V =((V>→2)及0x33333333)| ((V&放大器; 0x33333333)下; 2);
//交换啃...
V =((V>→4)及0x0F0F0F0F)| ((V&放大器; 0x0F0F0F0F)所述; 4;);
//交换字节
V =((V>→8)及0x00FF00FF)| ((V&放大器; 0x00FF00FF)所述;&下; 8);
//交换2字节长对
V =(V>> 16)| (V族;&下; 16);


Possible Duplicate:
C reverse bits in unsigned integer

How can I reverse a binary number only using binary operators?

E.g:

11100000 -> 00000111
00110100 -> 00101100
00111111 -> 11111100

解决方案

For this sort of thing I recommend that you take a look at the awesome page Bit Twiddling Hacks.

Here is just one example solution taken from that page:

Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division)

unsigned char b; // reverse this (8-bit) byte 
b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;

And as pointed out in the comments, here's another option:

Reverse an N-bit quantity in parallel in 5 * lg(N) operations

unsigned int v; // 32-bit word to reverse bit order

// swap odd and even bits
v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);
// swap consecutive pairs
v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);
// swap nibbles ... 
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);
// swap bytes
v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = ( v >> 16             ) | ( v               << 16);

这篇关于c反向二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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