C:构建一个字节

时间:2010-03-06 19:59:03

标签: c binary byte

我有一个包含16个元素的数组。我想将这些值计算为布尔值0或1,然后将其存储在2个字节中,以便我可以写入二进制文件。我该怎么做?

6 个答案:

答案 0 :(得分:4)

你的意思是这样的吗?

unsigned short binary = 0, i;
for ( i = 0; i < 16; ++i )
  if ( array[i] )
    binary |= 1 << i; 

// the i-th bit of binary is 1 if array[i] is true and 0 otherwise.

答案 1 :(得分:2)

您必须使用bitwise operators

以下是一个例子:

int firstBit = 0x1;
int secondBit = 0x2;
int thirdBit = 0x4;
int fourthBit = 0x8;

int x = firstBit | fourthBit; /*both the 1st and 4th bit are set */
int isFirstBitSet = x & firstBit; /* Check if at least the first bit is set */

答案 2 :(得分:2)

int values[16];
int i;
unsigned short word = 0;
unsigned short bit = 1;

for (i = 0; i < 16; i++)
{
    if (values[i])
    {
        word |= bit;
    }

    bit <<= 1;
}

答案 3 :(得分:2)

此解决方案避免在循环内使用if:

unsigned short binary = 0, i;
for ( i = 0; i < 16; ++i )
  binary |= (array[i] != 0) << i;

答案 4 :(得分:1)

声明一个包含两个字节的数组result,然后循环遍历源数组:

for (int i = 0; i < 16; i++) {
  // calclurate index in result array
  int index = i >> 3;
  // shift value in result
  result[index] <<= 1;
  // check array value
  if (theArray[i]) {
    // true, so set lowest bit in result byte
    result[index]++;
  }
}

答案 5 :(得分:-1)

像这样。

int values[16];
int bits = 0;
for (int ii = 0; ii < 16; ++ii)
{
    bits |= (!!values[ii]) << ii;
}

unsigned short output = (unsigned short)bits;

表达式(!! values [ii])强制该值为0或1,如果您确定值数组已经包含0或1而没有别的,则可以离开!!

如果你不喜欢!!你也可以这样做!句法。

int values[16];
int bits = 0;
for (int ii = 0; ii < 16; ++ii)
{
    bits |= (values[ii] != 0) << ii;
}

unsigned short output = (unsigned short)bits;