在Arduino C中将两个二进制数交织在一起

时间:2017-11-18 17:43:29

标签: c# arduino binary arduino-uno binary-data

所以我遇到了一个奇怪的需求,即合并'两个数字:

byte one;
byte two;

进入int three;,第一位是one的第一位,第二位是two的第一位,第三位是one的第二位等等。

所以这两个数字:

01001000
00010001

会导致

0001001001000010

隔行扫描操作的更为详尽的说明:

byte one = 0  1  0  0  1  0  0  0
byte two = 0  0  0  1  0  0  0  1
result   = 00 01 00 10 01 00 00 10

2 个答案:

答案 0 :(得分:1)

更新:抱歉完全误读了您的问题。

以下代码应该:

public static int InterlacedMerge(byte low, byte high)
{
    var result = 0;

    for (var offset = 0; offset < 8; offset++)
    {
        var mask = 1 << offset;
        result |= ((low & mask) | ((high & mask)) << 1) << offset;
    }

    return result;
}
无论如何,当涉及到微不足道时,我并不是非常聪明,所以可能有更有效的方法来做到这一点。也就是说,我认为这样可以完成这项工作,但我还没有对它进行测试,所以请确保你这样做。

P.D:代码中有一些不必要的括号,但我不确定按位运算符的优先级,所以我发现它更容易阅读它的编写方式。

UPDATE2:以下是相同的代码,使其更容易理解:

public static int InterlacedMerge(byte low, byte high)
{
    var result = 0;

    for (var offset = 0; offset < 8; offset++)
    {
        //Creates a mask with the current bit set to one: 00000001,
        //00000010, 00000100, and so on...
        var mask = 1 << offset; 

        //Creates a number with the current bit set to low's bit value.
        //All other bits are 0
        var lowAndMask = low & mask; 

        //Creates a number with the current bit set to high's bit value.
        //All other bits are 0
        var highAndMask = high & mask; 

        //Create a merged pair where the lowest bit is the low 's bit value
        //and the highest bit is high's bit value.
        var mergedPair = lowAndMask | (highAndMask << 1);

        //Ors the mergedPair into the result shifted left offset times
        //Because we are merging two bits at a time, we need to
        //shift 1 additional time for each preceding bit.                              
        result |= mergedPair << offset;
    }

    return result;
}

答案 1 :(得分:1)

在我写这篇文章的时候,@ inbetween回答了;类似的解决方案,不同的措辞。

你必须写一个循环。您将在两个输入中的每一个中测试一位。您将在每个输入的输出中设置一个位。你将把所有三个值都移到一个位置。也许是这样的(未经测试):

#define TOPBIT 32768

for /* 16 times */
    if ( value1 & 1 )  out |= TOPBIT;
    out >>= 1;

    if ( value2 & 1 )  out |= TOPBIT;
    out >>= 1;

    b1 >>= 1;
    b2 >>= 1;