我有一系列半字节(0x0 - 0xF)和一个产生清晰模式的转换结果。转型解决方案根本不是来找我(不是因为缺乏尝试)。是否有一位经验丰富的人在那里认识到这种转变?提前谢谢。
0 -> 0
1 -> 1
2 -> 1
3 -> 0
----------
4 -> 2
5 -> 3
6 -> 3
7 -> 2
----------
8 -> 7
9 -> 6
A -> 6
B -> 7
----------
C -> 5
D -> 4
E -> 4
F -> 5
答案 0 :(得分:3)
看一下各个位,输入和输出之间的一个可能关系似乎是:
Y0 = X0^X1^X3
Y1 = X2^X3
Y2 = X3
Y3 = 0
其中X0..X3是输入位,Y0..Y3是输出位。
然而,这需要大约10个或更多的按位操作来实现,所以最好只使用查找表。
这是C中的一个测试程序,用于验证按位逻辑是否正确:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
static int convert_bitwise(int x)
{
int x0 = x & 1;
int x1 = (x & 2) >> 1;
int x2 = (x & 4) >> 2;
int x3 = x >> 3;
int y0 = x0 ^ x1 ^ x3;
int y1 = x2 ^ x3;
int y2 = x3;
return (y2 << 2) | (y1 << 1) | y0;
}
static int convert_lut(int x)
{
const int LUT[16] = { 0, 1, 1, 0,
2, 3, 3, 2,
7, 6, 6, 7,
5, 4, 4, 5 };
return LUT[x & 0x0f];
}
int main(int argc, char *argv[])
{
int x;
for (x = 0; x < 16; ++x)
{
int y_bitwise = convert_bitwise(x);
int y_lut = convert_lut(x);
printf("x = %2d, y (bitwise) = %d, y (LUT) = %d, (%s)\n", x, y_bitwise, y_lut, y_bitwise == y_lut ? "PASS" : "FAIL");
}
return 0;
}
测试:
$ gcc -Wall bits4.c && ./a.out
x = 0, y (bitwise) = 0, y (LUT) = 0, (PASS)
x = 1, y (bitwise) = 1, y (LUT) = 1, (PASS)
x = 2, y (bitwise) = 1, y (LUT) = 1, (PASS)
x = 3, y (bitwise) = 0, y (LUT) = 0, (PASS)
x = 4, y (bitwise) = 2, y (LUT) = 2, (PASS)
x = 5, y (bitwise) = 3, y (LUT) = 3, (PASS)
x = 6, y (bitwise) = 3, y (LUT) = 3, (PASS)
x = 7, y (bitwise) = 2, y (LUT) = 2, (PASS)
x = 8, y (bitwise) = 7, y (LUT) = 7, (PASS)
x = 9, y (bitwise) = 6, y (LUT) = 6, (PASS)
x = 10, y (bitwise) = 6, y (LUT) = 6, (PASS)
x = 11, y (bitwise) = 7, y (LUT) = 7, (PASS)
x = 12, y (bitwise) = 5, y (LUT) = 5, (PASS)
x = 13, y (bitwise) = 4, y (LUT) = 4, (PASS)
x = 14, y (bitwise) = 4, y (LUT) = 4, (PASS)
x = 15, y (bitwise) = 5, y (LUT) = 5, (PASS)
$