如何读取1个标志位并同时获取整数 [英] How to read off 1 flag bit and get integer at same time

查看:67
本文介绍了如何读取1个标志位并同时获取整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个8位数字,两侧都有一个标志:

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.

推荐答案

您可以使用结尾处的标志来做类似的事情:

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

但是二进制操作和位标志一般来说都是对JavaScript的一种滥用,因为它实际上没有整数类型.但是,如果确实需要这样做,则末尾的标志似乎更可靠,因为您不能明确保证数字的类型为8位.这样,标志将始终位于同一位置,其余部分将始终是您的号码.

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.

这篇关于如何读取1个标志位并同时获取整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆