How do I print one bit?

后端 未结 6 403
野性不改
野性不改 2021-01-18 04:30

Please tell me how do I print a bit, like printf(\"%d\",bit);.

相关标签:
6条回答
  • 2021-01-18 05:02

    You can use "union":

    union bitshow {
        unsigned bit1:1;
        int i;
    };
    
    int main() {
        union bitshow bit;
        cin >> bit.i;
        cout << bit.bit1;
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-18 05:03

    The C++ answer is easier than the C89 one, with the native bool type:

    bool b = true;
    std::cout << b;
    

    C99 is quite similar:

    _Bool b = 1;
    printf("%d", b);
    
    0 讨论(0)
  • 2021-01-18 05:04

    If bit is just an int that contains the value you want in the least significant bit, then:

    printf("%d", bit & 0x1);
    

    should do it. The & is doing a binary-AND with a number with only the first significant bit set, so you're removing all the rest of the bits in the integer.

    0 讨论(0)
  • 2021-01-18 05:10

    To print the m-th bit (m from 1..16 or 32) of n:

    void print_bit(n, m)
    {
        printf("%d", n & (1 << (m - 1)));
    }
    

    Remove the - 1 bit if your bit counter starts at 0.

    0 讨论(0)
  • 2021-01-18 05:16

    Related question: How do you set, clear, and toggle a single bit? is an extended discussion of single-bit access in c and c++.

    0 讨论(0)
  • 2021-01-18 05:19

    If you need to generalize more than Herms, you could do this:

    #define IsBitSet(val, bit) ((val) & (1 << (bit)))
    
    /* ... your code ... */
    
    printf ("%c", IsBitSet(bit, 0) ? '1' : '0');
    

    The printf is equivalent to Herms answer as is.

    If you're talking about bitfield in C, you can do this:

    struct foo { int b:1; } myFoo;
    
    printf("%c", myFoo.b ? '1' : '0');
    
    0 讨论(0)
提交回复
热议问题