我要如何为int的低8位? [英] How do i get the lower 8 bits of int?
本文介绍了我要如何为int的低8位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以说我有一个int变量N = 8。在大多数机器上,这将是一个32位值。我怎么只能得到这样的低8位(最低字节)的二进制?此外,我怎么能访问每一个位,找出它是什么?
我的问题是有关为C
解决方案
无符号的N = 8;
无符号low8bits = N&安培; 0xFF的;
请注意以下几点:
- 对于位操作,始终使用
无符号
类型 - 位可以使用二进制遮蔽与数字提取
&安培;
运营商 - 要访问的低8位掩码是
0xFF的
,因为在二元它有它的低8位开启,其余0 - 数字8的低8位是... 8(想想了一会儿)
要访问大量的某一点,说 K
个位:
无符号N = ...;
无符号kthbit =(1 <<;&所述; k)及N;
现在, kthbit
将是0,如果 K
个位 N
0,有的正数( 2 **亩
)如果 K
次的位 N
1
Lets say I have an int variable n = 8. On most machines this will be a 32 bit value. How can I only get the lower 8 bits (lowest byte) of this in binary? Also how can i access each bit to find out what it is? My question is related to C
解决方案
unsigned n = 8;
unsigned low8bits = n & 0xFF;
Note a few things:
- For bitwise operations, always use the
unsigned
types - Bits can be extracted from numbers using binary masking with the
&
operator - To access the low 8 bits the mask is
0xFF
because in binary it has its low 8 bits turned on and the rest 0 - The low 8 bits of the number 8 are... 8 (think about it for a moment)
To access a certain bit of a number, say the k
th bit:
unsigned n = ...;
unsigned kthbit = (1 << k) & n;
Now, kthbit
will be 0 if the k
th bit of n
is 0, and some positive number (2**k
) if the k
th bit of n
is 1.
这篇关于我要如何为int的低8位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文