How to read off 1 flag bit and get integer at same time

筅森魡賤 提交于 2019-12-25 02:29:14

问题


Say I have an 8-bit number with a flag at either side:

<flag>0101011 (decimal 43)
0101011<flag> (decimal 43)

Not sure which is more optimal for what's next.

Then say I want to check the flag, and then use the number. Wondering if that can be done in one operation. Or if not, the fewest operations it can be done in.


回答1:


You could do something like this using the flag at the end:

var num = 0b01010110;
var flag = num & 1;
var int = num >> 1;
console.log(flag);
console.log(int);

But binary operations and bit flags in general are kind of an abuse of JavaScript since it doesn't really have integer types. If you do need to do it though, it seems like a flag at the end would be more reliable since you can't explicitly guarantee a number to be 8 bits by its type. This way the flag will always be in the same position and the rest will always be your number.



来源:https://stackoverflow.com/questions/52045509/how-to-read-off-1-flag-bit-and-get-integer-at-same-time

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