代码之家  ›  专栏  ›  技术社区  ›  AlwaysNeedingHelp

在Arduino C中交错两个二进制数

  •  1
  • AlwaysNeedingHelp  · 技术社区  · 8 年前

    所以我遇到了一种奇怪的需要,需要“合并”两个数字:

    byte one;
    byte two;
    

    变成一个 int three; 第一位是 one two ,第三个是 等等

    有了这两个数字:

    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 回复  |  直到 7 年前
        1
  •  1
  •   InBetween    8 年前

    更新:对不起,完全误读了你的问题。

    以下代码应执行以下操作:

    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;
    }
    
        2
  •  1
  •   aMike    8 年前

    @在我写这封信的时候,他回答了我的问题;相似的解决方案,不同的措辞。

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

    #define TOPBIT 32768
    
    for /* 16 times */
        if ( value1 & 1 )  out |= TOPBIT;
        out >>= 1;
    
        if ( value2 & 1 )  out |= TOPBIT;
        out >>= 1;
    
        b1 >>= 1;
        b2 >>= 1;