0

我已经做好了

uint32_t bits= 0;

bits |= 1<< 31;

然后使用

void printbits(uint32_t n) {
    if (n) {
        printbits(n >> 1);
        printf("%d", n & 1);
    }
}

在位上我得到 10000000000000000000000000000000,这是我想要的,但是当我使用我的 getbit(bits, 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,知道为什么吗?

谢谢!

4

2 回答 2

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

于 2013-11-15T13:06:21.697 回答
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
于 2013-11-16T05:41:12.503 回答