屏蔽并提取C中的位 [英] Mask and extract bits in C
问题描述
我一直在寻找有关遮罩的帖子,但仍然无法理解如何从C中的数字中提取某些位.
I've been looking at posts about mask but still can't get my head around how to extract certain bits from a number in C.
假设我们有一个int number 0001 1010 0100 1011
,那么它的十六进制表示形式是x1a4b
对吗?如果我想知道第5到第7个数字(在这种情况下为101
),我应该使用int mask= 0x0000 1110 0000 0000, int extract = mask&number
吗?
Say if we have a int number 0001 1010 0100 1011
, so it's hex representation is x1a4b
right? If I want to know the 5th to 7th number, which is 101
in this case, shall I use int mask= 0x0000 1110 0000 0000, int extract = mask&number
?
我又如何检查它是否为101
?我想==
在这里不起作用...非常感谢!
Also how can I check if it is 101
? I guess ==
won't work here... Many thanks!
推荐答案
假定gcc扩展0b
定义二进制文字:
Assuming the gcc extension 0b
to define binary literals:
int number = 0b0001101001001011; /* 0x1a4b */
int mask = 0b0000111000000000; /* 0x0e00 */
/* &'ed: 0b0000101000000000; 0x0a00 */
int extract = mask & number; /* 0x0a00 */
if (extract == 0b0000101000000000)
/* or if 0b is not available:
if (extract == 0x0a00 ) */
{
/* success */
}
else
{
/* failure */
}
这篇关于屏蔽并提取C中的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!