我已经完成了
uint32_t bits= 0;
bits |= 1<< 31;
然后使用
void printbits(uint32_t n) {
if (n) {
printbits(n >> 1);
printf("%d", n & 1);
}
}
在我得到10000000000000000000000000000000的位上,这是我想要的,但当我使用我的getbit(位,0)时
int get_bit(int n, int bitnr) {
int mask = 1 << bitnr;
int masked_n = n & mask;
int thebit = masked_n >> bitnr;
return thebit;
}
我得到-1而不是1,任何想法为什么?
感谢的!
答案 0 :(得分:4)
向右移动已签名的号码,如果号码为负,则为实施行为。
根据最新标准草案的第6.5.7节,负数的这种行为取决于实现:
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an
unsigned type or if E1 has a signed type and a nonnegative value, the value of
the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed
type and a negative value, the resulting value is implementation-defined.
修改强> 请参考这里如何表示数字https://stackoverflow.com/a/16728502/1814023
答案 1 :(得分:1)
这就是你想要的。
#include <stdio.h>
void printbits(int n);
int get_bit(int n, int bitnum);
int
main()
{
int bits = 0;
bits |= 1 << 31;
printbits(bits);
bits = 0xf0f0f0f0;
printbits(bits);
return(0);
}
void
printbits(int n)
{
int j;
for (j = 0; j < 32; j++) {
printf("%d", get_bit(n, j));
}
printf("\n");
}
int
get_bit(int n, int bitnum)
{
return((n >> (31 - bitnum)) & 1);
}
编译运行时,应输出
10000000000000000000000000000000
11110000111100001111000011110000