C: Building a byte

时光总嘲笑我的痴心妄想 提交于 2020-01-23 19:44:21

问题


I have an array with 16 elements. I would like to evaluate these to a boolean 0 or 1 and then store this in 2 bytes so i can write to a binary file. How do I do this?


回答1:


Something like this you mean?

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.



回答2:


You have to use bitwise operators.

Here's an example:

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 */



回答3:


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;
}



回答4:


This solution avoid the use of the if inside the loop:

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



回答5:


Declare an array result with two bytes, then you loop through the source array:

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]++;
  }
}



回答6:


Something like this.

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

unsigned short output = (unsigned short)bits;

the expression (!!values[ii]) forces the value to be 0 or 1, if you know for sure that the values array already contains either a 0 or a 1 and nothing else, you can leave of the !!

You could also do this if you don't like the !! syntax.

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

unsigned short output = (unsigned short)bits;


来源:https://stackoverflow.com/questions/2393914/c-building-a-byte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!