Pushing boolean values of an array to uint8 bitfield

こ雲淡風輕ζ 提交于 2020-01-05 07:23:12

问题


Let's suppose I have:

myArray[7] = {TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE}

uint8 mybitfield;

What is the most efficient way to "push" those values to an uint8 bitfield with 0=FALSE, 1=TRUE

So that mybitfield is represented as:

[1,0,0,1,1,0,0,0] 

(The Least Significant Bit is not considered and will be always 0).

Thanks!


回答1:


As already noted, you have to iterate over the bits individually, for example:

int myArray[7] = {TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE};

uint8_t bitfield = 0;
for (int i = 0; i < 7; ++i) {
    bitfield |= myArray[i] ? 1 : 0;
    bitfield <<= 1;
}

This results in 0b10011000, i.e., the array has the most significant bit first and an implicit zero for the least significant bit.




回答2:


With myArray being some generic integer type, there's really no other way than to iterate across all items in the array, if TRUE then set bit i with bitfield |= 1u << i;.



来源:https://stackoverflow.com/questions/59071101/pushing-boolean-values-of-an-array-to-uint8-bitfield

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