[英]How to combine 2 4-bit unsigned numbers into 1 8-bit number in C
I have 2 4-bit numbers (X0X1X2X3 and Y0Y1Y2Y3) and I want to combine them so that I would create an 8-bit number like that:我有 2 个 4 位数字(X0X1X2X3 和 Y0Y1Y2Y3),我想将它们组合起来,这样我就可以创建一个这样的 8 位数字:
X0X1X2X3
Y0Y1Y2Y3 => X0Y0X1Y1X2Y2X3Y3
I know how to concatenate them in order to create the X0X1X1X3Y0Y1Y2Y3
but I am stuck on how to compose them in the pattern explained above.我知道如何将它们连接起来以创建
X0X1X1X3Y0Y1Y2Y3
但我坚持如何按照上述模式组合它们。
Any hints?任何提示?
A very quick way of interleaving four-bit numbers is with a look-up table:交织四位数字的一种非常快速的方法是使用查找表:
unsigned int spread[] = {
0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15,
0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55
};
You can use spread[]
array, which "spreads" bits of the original, to construct your output as follows:您可以使用
spread[]
数组,它“传播”原始位,按如下方式构建您的输出:
unsigned int res = (spread[x] << 1) | spread[y];
The trick is in the construction of the look-up table.诀窍在于构建查找表。 Its values are selected in such a way that the bits of the index are interleaved with zeros.
其值的选择方式是索引的位与零交错。 For example,
0x07
, or 0111 2 , becomes 0x15
, or 00010101 2 .例如,
0x07
或 0111 2变为0x15
或 00010101 2 。
Here's a fairly direct way of performing this transformation:这是执行此转换的一种相当直接的方法:
uint8_t result;
result |= (x & 8) << 4;
result |= (y & 8) << 3;
result |= (x & 4) << 3;
result |= (y & 4) << 2;
result |= (x & 2) << 2;
result |= (y & 2) << 1;
result |= (x & 1) << 1;
result |= (y & 1) << 0;
您也可以在一行中执行此操作。
uint8_t result = (varX << 4) | (varY);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.