我没有得到字节值?

时间:2018-09-28 19:23:17

标签: c algorithm

执行以下代码时,我无法获得正确的输出。查看我要打印的评论。

我根据到目前为止所学的知识编写了代码,但是仍然没有得到正确的输出。

那么有什么建议吗?我做了什么,所以我能够解决问题。 当我打印(A)时,我没有得到0100 0001,但有时会打印49d49

#include <stdio.h>

unsigned char getBit(unsigned char c, int n)
{
    return ((c & (1 << n)) >> n);
}
unsigned char setBit(unsigned char c, int n)
{
    c = c | (1 << n);
    return c;
}

unsigned char clearBit(unsigned char c, int n)
{
    c = c & (~(1 << n));
    return c;
}

void printBits(unsigned char c)
{
    printf("The bit of the character you inputed is %x \n", c);
}

int main(void)
{
    unsigned char a = 'A';
    printBits(a);
    putchar('\n');

    a = setBit(a, 2);
    a = setBit(a, 3);
    printBits(a);  //should print 0100 0001, but it prints 49
    putchar('\n');

    a = clearBit(a, 2);
    printBits(a);
    putchar('\n');
}

1 个答案:

答案 0 :(得分:0)

您当前的解决方案使用cprintf()的值打印为十六进制数。由于没有printf格式说明符以二进制形式打印数字,因此我们必须编写自己的解决方案。

#include <limits.h>
#include <stdio.h>

void printBits(byte c)
{
    for (unsigned i = CHAR_BIT; i;) { // count from the with of a char
                                      // in bits down to 1
        putchar(c & 1 << --i  // test the i-th bit (1-based)
            ? '1'         // if true (different form 0) evaluates to '1'
            : '0'         // else evaluates to '0'
        );
        if (CHAR_BIT == 8 && i % 4 == 0)  // if we use 8-bit-bytes and just
                                          // finished printing the higher nibble
            putchar(' ');  // insert a seperator between the nibbles
    }
}

... ftw!

废话版:

void printBits(byte c)
{
    for (unsigned i = CHAR_BIT; i;) {
        putchar(c & 1 << --i ? '1' : '0');
        if (CHAR_BIT == 8 && !(i % 4))
            putchar(' ');
    }
}

`

unsigned char a = 'A';
printBits(a);  // should print 0100 0001
putchar('\n');

a = setBit(a, 2); 
a = setBit(a, 3); 
printBits(a);  // should print 0100 1101
putchar('\n');

a = clearBit(a, 2);
printBits(a);  // should print 0100 1001
putchar('\n'