提取与位运算符位 [英] Extracting bits with bitwise operators
问题描述
我想学习如何使用位运算符在给定的输入,但我没有多少运气搞清楚如何使用它们。
I'm trying to learn how to use bitwise operators on a given input but am not having much luck figuring out how to use them.
让我们说我有这八位如下:
Let's say I have this following octet:
11(01)0000
我将如何提取括号之间的位?
How would I extract the bits between the braces?
推荐答案
您需要:
-
创建只有那些你是哪里需要字节(你只需要编写二进制数并转换为十六进制例如把它的C程序中)合适的面具。在你的
中的括号11(01)0000
是你的指示在何处放置的那些在你的面具。
create a suitable mask with ones only where are the bytes you need (you just need to write the number in binary and convert to e.g. hex to put it inside the C program). The parentheses in your
11(01)0000
are your indication to where to put the ones in your mask.
另外,创建由尽可能多的,你有兴趣的比特块(面具你的情况两个1,即 11
二进制,即 3
十进制)和左移它它移动到你需要的位置,它(向左移位运算符:<<
)。如果你的位窗口的位置,只在运行时已知此方法可能是有用的。
Alternatively, create a mask made of as many ones as the chunk of bits you are interested in (in your case two ones, i.e. 11
in binary, i.e. 3
in decimal) and left shift it to move it to the position where you need it (left shift operator: <<
). This approach can be useful if the position of your "bit window" is known only at runtime.
执行你的电话号码和掩码之间的按位与操作(按位和操作是&安培;
)。
Perform a bitwise-and operation between your number and the mask (the bitwise and operator is &
).
按位,只留下为1,在这两个操作数是1位,所以效果是过滤与掩码位源编号:对应于那些在掩码只有位让流过吧,所有其他位保持为零。
The bitwise and only leaves as 1 the bits that are 1 in both the operands, so the effect is "filtering" the source number with the bits of the mask: only the bits that correspond to ones in the mask are let "flow through" it, all the other bits are left as zero.
现在你已经提取你感兴趣的位,但他们还是在数量内原来的位置。如果你想/需要它,那么你可以用鼠标右键将它们转移到它们右对齐。(使用右移位运算符:&GT;&GT;
)
Now you have extracted the bits of your interest, but they are still in their original position inside the number. If you want/need it, you can then right shift them to "align them to the right" (use the right shift operator: >>
).
这篇关于提取与位运算符位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!