nat*_*han 101 c c++ bit-manipulation
虽然有多种方法可以在一个字节中反转位顺序,但我很好奇开发人员实现的"最简单".通过颠倒我的意思是:
1110 -> 0111
0010 -> 0100
Run Code Online (Sandbox Code Playgroud)
这与此 PHP问题类似,但不重复.
这与此 C问题类似,但不重复.这个问题要求开发人员实施最简单的方法."最佳算法"涉及内存和CPU性能.
sth*_*sth 214
这应该工作:
unsigned char reverse(unsigned char b) {
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
return b;
}
Run Code Online (Sandbox Code Playgroud)
首先,左四位与右四位交换.然后交换所有相邻对,然后交换所有相邻的单个位.这导致相反的顺序.
def*_*ode 116
我认为查找表必须是最简单的方法之一.但是,您不需要完整的查找表.
//Index 1==0b0001 => 0b1000
//Index 7==0b0111 => 0b1110
//etc
static unsigned char lookup[16] = {
0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe,
0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf, };
uint8_t reverse(uint8_t n) {
// Reverse the top and bottom nibble then swap them.
return (lookup[n&0b1111] << 4) | lookup[n>>4];
}
// Detailed breakdown of the math
// + lookup reverse of bottom nibble
// | + grab bottom nibble
// | | + move bottom result into top nibble
// | | | + combine the bottom and top results
// | | | | + lookup reverse of top nibble
// | | | | | + grab top nibble
// V V V V V V
// (lookup[n&0b1111] << 4) | lookup[n>>4]
Run Code Online (Sandbox Code Playgroud)
这在视觉上进行编码和验证相当简单.
最终,这甚至可能比完整的表更快.位数便宜,表格很容易适合缓存行.
e.J*_*mes 94
如果你在谈论单个字节,那么表查找可能是最好的选择,除非由于某种原因你没有256字节可用.
Ark*_*kku 45
对于许多解决方案,请参阅讨厌的黑客攻击.从那里进行复制显然很容易实现.=)
例如(在32位CPU上):
uint8_t b = byte_to_reverse;
b = ((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
Run Code Online (Sandbox Code Playgroud)
如果通过"简单实施"意味着可以在考试或求职面试中没有参考的情况下完成,那么最安全的赌注可能是以相反的顺序将比特一个接一个地复制到另一个变量中(已在其他答案中显示) ).
fre*_*low 38
由于没有人发布完整的表查找解决方案,这是我的:
unsigned char reverse_byte(unsigned char x)
{
static const unsigned char table[] = {
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
};
return table[x];
}
Run Code Online (Sandbox Code Playgroud)
and*_*and 25
template <typename T>
T reverse(T n, size_t b = sizeof(T) * CHAR_BIT)
{
assert(b <= std::numeric_limits<T>::digits);
T rv = 0;
for (size_t i = 0; i < b; ++i, n >>= 1) {
rv = (rv << 1) | (n & 0x01);
}
return rv;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
使用可选的bitcount将其转换为模板
Dan*_*iel 16
两行:
for(i=0;i<8;i++)
reversed |= ((original>>i) & 0b1)<<(7-i);
Run Code Online (Sandbox Code Playgroud)
如果您遇到"0b1"部分的问题:
for(i=0;i<8;i++)
reversed |= ((original>>i) & 1)<<(7-i);
Run Code Online (Sandbox Code Playgroud)
"original"是您要反转的字节."反转"是结果,初始化为0.
Tho*_*ews 13
虽然可能不便携,但我会使用汇编语言.
许多汇编语言都有指令将一位旋转到进位标志并将进位标志旋转到字(或字节)中.
算法是:
for each bit in the data type:
rotate bit into carry flag
rotate carry flag into destination.
end-for
Run Code Online (Sandbox Code Playgroud)
高级语言代码要复杂得多,因为C和C++不支持旋转来携带和旋转.进位标志必须建模.
编辑: 汇编语言例如
; Enter with value to reverse in R0.
; Assume 8 bits per byte and byte is the native processor type.
LODI, R2 8 ; Set up the bit counter
Loop:
RRC, R0 ; Rotate R0 right into the carry bit.
RLC, R1 ; Rotate R1 left, then append carry bit.
DJNZ, R2 Loop ; Decrement R2 and jump if non-zero to "loop"
LODR, R0 R1 ; Move result into R0.
Run Code Online (Sandbox Code Playgroud)
dau*_*ama 12
我发现以下解决方案比我在这里看到的其他比特摆弄算法更简单.
unsigned char reverse_byte(char a)
{
return ((a & 0x1) << 7) | ((a & 0x2) << 5) |
((a & 0x4) << 3) | ((a & 0x8) << 1) |
((a & 0x10) >> 1) | ((a & 0x20) >> 3) |
((a & 0x40) >> 5) | ((a & 0x80) >> 7);
}
Run Code Online (Sandbox Code Playgroud)
它获取字节中的每一位,并相应地将其移位,从第一个开始到最后一个.
说明:
((a & 0x1) << 7) //get first bit on the right and shift it into the first left position
| ((a & 0x2) << 5) //add it to the second bit and shift it into the second left position
//and so on
Run Code Online (Sandbox Code Playgroud)
Ant*_*REL 11
根据您的意思是“最简单的方法”,有很多方法可以反转位。
可能是最合乎逻辑的,包括在对第一位应用掩码的同时旋转字节(n & 1)
:
unsigned char reverse_bits(unsigned char b)
{
unsigned char r = 0;
unsigned byte_len = 8;
while (byte_len--) {
r = (r << 1) | (b & 1);
b >>= 1;
}
return r;
}
Run Code Online (Sandbox Code Playgroud)
由于 unsigner char 的长度为 1 个字节,等于 8 位,这意味着我们将扫描每一位 while (byte_len--)
我们首先检查 b 是否为最右边的位(b & 1)
;如果是这样,我们在 r 上设置位 1|
并通过将 r 乘以 2 将其向左移动 1 位(r << 1)
然后我们将无符号字符 b 除以 2b >>=1
以擦除位于变量 b 最右侧的位。提醒一下,b >>= 1; 相当于 b /= 2;
此解决方案归功于“编程黑客”部分中的 Rich Schroeppel
unsigned char reverse_bits3(unsigned char b)
{
return (b * 0x0202020202ULL & 0x010884422010ULL) % 0x3ff;
}
Run Code Online (Sandbox Code Playgroud)
乘法运算 (b * 0x0202020202ULL) 创建 8 位字节模式的五个单独副本,以扇出为 64 位值。
AND 运算 (& 0x010884422010ULL) 选择相对于每个 10 位位组处于正确(反转)位置的位。
乘法和与运算一起从原始字节复制位,因此它们每个都只出现在 10 位集合中的一个中。与原始字节相反的位的位置与它们在任何 10 位集合中的相对位置一致。
最后一步 (% 0x3ff) 涉及模数除以 2^10 - 1 的作用是将每组 10 位(从位置 0-9、10-19、20-29、...)合并在一起。 64 位值。它们不重叠,因此模数除法基础的加法步骤的行为类似于 OR 运算。
unsigned char reverse(unsigned char b) {
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
return b;
}
Run Code Online (Sandbox Code Playgroud)
这是最受欢迎的答案,尽管有一些解释,但我认为对于大多数人来说,很难想象 0xF0、0xCC、0xAA、0x0F、0x33 和 0x55 的真正含义。
它没有利用'0b',它是一个GCC 扩展,自 2014 年 12 月发布的 C++14 标准以来就包含在内,所以在这个答案可追溯到 2010 年 4 月之后的一段时间
整数常量可以写成二进制常量,由“0”和“1”数字序列组成,前缀为“0b”或“0B”。这在位级(如微控制器)大量运行的环境中特别有用。
请检查下面的代码片段,以记住并更好地理解我们将一半移动的解决方案:
unsigned char reverse(unsigned char b) {
b = (b & 0b11110000) >> 4 | (b & 0b00001111) << 4;
b = (b & 0b11001100) >> 2 | (b & 0b00110011) << 2;
b = (b & 0b10101010) >> 1 | (b & 0b01010101) << 1;
return b;
}
Run Code Online (Sandbox Code Playgroud)
注意:这>> 4
是因为 1 字节中有 8 位,这是一个无符号字符,所以我们要取另一半,依此类推。
我们可以轻松地将此解决方案应用于 4 个字节,只需添加两行并遵循相同的逻辑。由于两个掩码相互补充,我们甚至可以使用 ~ 来切换位并节省一些墨水:
uint32_t reverse_integer_bits(uint32_t b) {
uint32_t mask = 0b11111111111111110000000000000000;
b = (b & mask) >> 16 | (b & ~mask) << 16;
mask = 0b11111111000000001111111100000000;
b = (b & mask) >> 8 | (b & ~mask) << 8;
mask = 0b11110000111100001111000011110000;
b = (b & mask) >> 4 | (b & ~mask) << 4;
mask = 0b11001100110011001100110011001100;
b = (b & mask) >> 2 | (b & ~mask) << 2;
mask = 0b10101010101010101010101010101010;
b = (b & mask) >> 1 | (b & ~mask) << 1;
return b;
}
Run Code Online (Sandbox Code Playgroud)
上面的逻辑可以用一个循环来总结,该循环适用于任何类型的无符号:
template <class T>
T reverse_bits(T n) {
short bits = sizeof(n) * 8;
T mask = ~T(0); // equivalent to uint32_t mask = 0b11111111111111111111111111111111;
while (bits >>= 1) {
mask ^= mask << (bits); // will convert mask to 0b00000000000000001111111111111111;
n = (n & ~mask) >> bits | (n & mask) << bits; // divide and conquer
}
return n;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用一个表来存储每个字节的反向值,并(i * 0x0202020202ULL & 0x010884422010ULL) % 0x3ff
通过 lambda 初始化(您需要使用它进行编译,g++ -std=c++1z
因为它仅适用于 C++17),然后返回表中的值将为您提供相应地反转位:
#include <cstdint>
#include <array>
uint8_t reverse_bits(uint8_t n) {
static constexpr array<uint8_t, 256> table{[]() constexpr{
constexpr size_t SIZE = 256;
array<uint8_t, SIZE> result{};
for (size_t i = 0; i < SIZE; ++i)
result[i] = (i * 0x0202020202ULL & 0x010884422010ULL) % 0x3ff;
return result;
}()};
return table[n];
}
Run Code Online (Sandbox Code Playgroud)
自己尝试包含上述功能:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
template <class T>
void print_binary(T n)
{ T mask = 1ULL << ((sizeof(n) * 8) - 1); // will set the most significant bit
for(; mask != 0; mask >>= 1) putchar('0' | !!(n & mask));
putchar('\n');
}
int main() {
uint32_t n = 12;
print_binary(n);
n = reverse_bits(n);
print_binary(n);
unsigned char c = 'a';
print_binary(c);
c = reverse_bits(c);
print_binary(c);
uint16_t s = 12;
print_binary(s);
s = reverse_bits(s);
print_binary(s);
uint64_t l = 12;
print_binary(l);
l = reverse_bits(l);
print_binary(l);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
最后但并非最不重要的一点,如果最简单意味着更少的行,为什么不尝试内联汇编?
您可以通过-masm=intel
在编译时添加来测试以下代码片段:
unsigned char reverse_bits(unsigned char c) {
__asm__ __volatile__ (R"(
mov cx, 8
daloop:
ror di
adc ax, ax
dec cx
jnz short daloop
;)");
}
Run Code Online (Sandbox Code Playgroud)
逐行解释:
mov cx, 8 ; we will reverse the 8 bits contained in one byte
daloop: ; while loop
shr di ; Shift Register `di` (containing value of the first argument of callee function) to the Right
rcl ax ; Rotate Carry Left: rotate ax left and add the carry from shr di, the carry is equal to 1 if one bit was "lost" from previous operation
dec cl ; Decrement cx
jnz short daloop; Jump if cx register is Not equal to Zero, else end loop and return value contained in ax register
Run Code Online (Sandbox Code Playgroud)
sth*_*sth 10
在最简单的方法可能是遍历在一个循环中位的位置:
unsigned char reverse(unsigned char c) {
int shift;
unsigned char result = 0;
for (shift = 0; shift < CHAR_BIT; shift++) {
if (c & (0x01 << shift))
result |= (0x80 >> shift);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
你可能感兴趣std::vector<bool>
(有点packed)和std::bitset
它应该是最简单的要求.
#include <iostream>
#include <bitset>
using namespace std;
int main() {
bitset<8> bs = 5;
bitset<8> rev;
for(int ii=0; ii!= bs.size(); ++ii)
rev[bs.size()-ii-1] = bs[ii];
cerr << bs << " " << rev << endl;
}
Run Code Online (Sandbox Code Playgroud)
其他选项可能更快.
编辑:我欠你一个解决方案 std::vector<bool>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<bool> b{0,0,0,0,0,1,0,1};
reverse(b.begin(), b.end());
copy(b.begin(), b.end(), ostream_iterator<int>(cerr));
cerr << endl;
}
Run Code Online (Sandbox Code Playgroud)
第二个示例需要c ++ 0x扩展(用于初始化数组{...}
).使用a bitset
或a std::vector<bool>
(或a boost::dynamic_bitset
)的优点是你不仅限于字节或字,而是可以反转任意数量的位.
HTH
对于恒定的8位输入,在运行时不需要内存或CPU:
#define MSB2LSB(b) (((b)&1?128:0)|((b)&2?64:0)|((b)&4?32:0)|((b)&8?16:0)|((b)&16?8:0)|((b)&32?4:0)|((b)&64?2:0)|((b)&128?1:0))
Run Code Online (Sandbox Code Playgroud)
我将此用于ARINC-429,其中标签的位顺序(字节顺序)与单词的其余部分相反.标签通常是常量,通常是八进制的.例如:
#define LABEL_HF_COMM MSB2LSB(0205)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
142038 次 |
最近记录: |