将一对位交换为一个字节 [英] Swapping pair of bits in a Byte
本文介绍了将一对位交换为一个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个任意的 8位二进制数字,例如 11101101
I have an arbitrary 8-bit binary number e.g., 11101101
我必须像这样交换所有对位:
I have to swap all the pair of bits like:
交换之前: 11-10-11-01
交换后: 11-01-11-10
在一次采访中有人问我!
I was asked this in an interview !
推荐答案
使用伪代码:
x = ((x & 0b10101010) >> 1) | ((x & 0b01010101) << 1)
它的工作原理是分别处理每个位对的低位和高位,然后组合结果:
It works by handling the low bits and high bits of each bit-pair separately and then combining the result:
- 表达式
x&0b10101010
从每对中提取高位,然后>>1
将其移至低位位置. - 类似地,表达式
(x& 0b01010101)<<1
从每对中提取低位,然后将其移到高位位置. - 然后使用按位或将这两部分组合在一起.
- The expression
x & 0b10101010
extracts the high bit from each pair, and then>> 1
shifts it to the low bit position. - Similarly the expression
(x & 0b01010101) << 1
extracts the low bit from each pair and shifts it to the high bit position. - The two parts are then combined using bitwise-OR.
由于并非所有语言都允许您直接编写二进制文字,因此可以用例如十六进制的形式编写它们:
Since not all languages allow you to write binary literals directly, you could write them in for example hexadecimal:
Binary Hexadecimal Decimal
0b10101010 0xaa 170
0b01010101 0x55 85
这篇关于将一对位交换为一个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文