繁体   English   中英

位操作; 将16位值转换为16个布尔值的数组? C语言

[英]Bit manipulation; Converting a 16-bit value into an array of 16 Boolean values? C language

我正在阅读一些代码,最后我需要弄清楚此函数的工作原理。 我了解它的用途以及为什么使用它,但除此之外,它还具有魔力。

据我了解,该函数采用一个值,该值将所有信息压缩到其中。 因此,不是将16个仅包含值0或1的整数打包,而是将每个0或1值打包到该整数的位中。 然后此函数将这些位取出,并将每个位放入一个char中。

该函数的调用方式如下

DecompressInputs(DigOut[0], &input[64]);

由于DigOut和input是这样定义的数组

UWORD DigOut[2];
char input[NUM_INPUTS]; // NUM_INPUTS = 80

和功能本身

/*===============================================*/
/* Name: DecompressInputs                        */
/* Purpose: Convert a 16 bit value into an array */
/*  of 16 boolean values.                        */
/*===============================================*/
static __inline__ void DecompressInputs(int bits,char *input)
{
    char i = 16;
    while(i)
    {
        if(bits & 0x0001)
            *input++ = 0x0a5;
        else
            *input++ = 0x000;

        bits = bits >> 1;   
        i-=1;
    }
}

该函数检查以bits为单位的LSB( if(bits & 0x0001) )。 如果设置了该位,则input的第一个char设置为'\\xa5' (可能是任何字符),否则设置为'\\0 然后input被incemented,使得在下一循环中的原始阵列的第二个字符将被设置并bits被移位( bits = bits >> 1;所以下一个循环将检查原始值的第二LSB。 执行16次以解压缩16位。

让我们举个例子:

位= 0x0005(二进制0000 0000 0000 0101)

然后我们有

  1. bits & 0x0001为true ==> input [0] ='\\ xa5'

    bits = bits >> 1 ==>位= 0x0002(二进制... 0010)

  2. bits & 0x0001为假==> input [1] ='\\ x00'(关于原始输入)

    bits = bits >> 1 ==>位= 0x0001(二进制... 0001)

  3. bits & 0x0001为true ==> input [2] ='\\ xa5'

    bits = bits >> 1 ==>位= 0x0000(二进制... 0000)

.. 等等

好的,让我们尝试解释这里发生的事情。

首先,我认为应该将static __inline__ void DecompressInputs(int bits,char *input)更新为static __inline__ void DecompressInputs(int bits,char *output)因为它看起来更像是输出值而不是输入值:这是细节。

让我们尝试使其更加清晰:

static __inline__ void DecompressInputs(int bits,char *output)
{
    char i = 16;
    while(i)
    {
        /* This will be true if the lowest bit of bits is 1. Otherwise, this is false */
        if(bits & 0x0001)
        {
         /* For whatever reason, you chose 0x0a5 to represent a bit whose value is 1. We write that value to the char pointed by output */
            *output = 0x0a5;
         /* Now that the value has been written, increment output so the next write will go the next char */
            output++;
        }
        else
        {
          /* Same here, but we store 0x00 instead */
            *output = 0x000;
            output++;
        }

        // Now we bitshift bits, so the next time we do bits & 0x0001, we will check for the second bit of the original integer
        bits = bits >> 1;   
        i-=1;
    }
}

此版本的代码可能更容易理解,因为它不那么依赖修改值:

static __inline__ void DecompressInputs(int bits, char *output)
{
    for (int bit = 0; bit < 16; ++bit)
    {
        int mask = 1 << bit;
        if (bits & mask)
            output[bit] = 0x0a5;
        else
            output[bit] = 0;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM