[英]Best way to grab 6 most significant bits from an unsigned int using operators in C?
I have managed to get rid of the first couple of bits but how would I only keep only the 6 most significant bits in C?我已经设法摆脱了前几个位,但是我如何只保留 C 中的 6 个最高有效位? I have tried
((num << 6) & 1)
with no luck我试过
((num << 6) & 1)
没有运气
To get the most significant six bits of an integer and not the rest, bitwise AND it with a mask with the high six bits set and the rest clear.要获得 integer 而不是 rest 的最高有效六位,请按位与设置高六位的掩码并清除 rest。
Because unsigned int
is a pure binary type, its maximum value, UINT_MAX
, has all its bits set.因为
unsigned int
是纯二进制类型,所以它的最大值UINT_MAX
的所有位都已设置。 Then UINT_MAX >> 6
shifts those to the right, producing a result with the high six bits clear and the rest set.然后
UINT_MAX >> 6
将它们向右移动,产生高六位清零和 rest 设置的结果。 Performing a bitwise NOT, ~ (UINT_MAX >> 6)
, produces a result with the high six bits set and the rest clear.执行按位 NOT,
~ (UINT_MAX >> 6)
会产生设置高六位且 rest 清除的结果。
Then num & ~ (UINT_MAX >> 6)
produces the high six bits of num
with the remaining bits clear.然后
num & ~ (UINT_MAX >> 6)
产生num
的高六位,其余位清零。
UINT_MAX
is declared in <limits.h>
. UINT_MAX
在<limits.h>
中声明。 Due to C's wrapping arithmetic for unsigned types, you can also get the maximum value of an unsigned int
by using -1u
, so num & ~ (-1u >> 6)
will also work.由于 C 对无符号类型的包装算法,您还可以使用
-1u
获得unsigned int
的最大值,因此num & ~ (-1u >> 6)
也可以使用。
Universal method not depending on the width of the integer通用方法不取决于 integer 的宽度
#define C6B(num) ((num) & ~((1ull << (sizeof(num) * CHAR_BIT - 6)) - 1))
OP wanted the 6 MSbits left in their original place . OP 希望将 6 个 MSbits 留在原来的位置。 Other answers address that.
其他答案解决了这个问题。
If we want these shifted into the least significant place, a common solution would look like the following.如果我们希望这些转移到最不重要的地方,一个常见的解决方案如下所示。 This assumes that an
unsigned
has 32 bits.这假设
unsigned
数具有 32 位。 Although common, this is not specified by C.虽然很常见,但 C 并未指定。
num >> (32 - 6)
Alternatively we could use the below.或者,我们可以使用下面的。 This assumes there are no padding bits, which is very common for
unsigned
.这假设没有填充位,这对于
unsigned
来说很常见。
#include <limits.h>
num >> (sizeof num * CHAR_BIT - 6)
Alternatively we could make no assumptions and determine bit width from UINT_MAX
and value bits of an integer type :或者,我们可以不做任何假设并从
UINT_MAX
和integer 类型的值位中确定位宽:
// Bits in a MAX integer type
// https://stackoverflow.com/a/4589384/2410359
#define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12))
#include <limits.h>
#define UINT_VALUE_BITS IMAX_BITS(UINT_MAX)
num >> (UINT_VALUE_BITS - 6)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.