Bytes to Binary in C

后端 未结 6 728
情书的邮戳
情书的邮戳 2021-02-04 14:22

I\'m trying to simply convert a byte received from fget into binary.

I know the value of the first byte was 49 based on printing the value. I now need to convert this in

6条回答
  •  被撕碎了的回忆
    2021-02-04 15:14

    One way, among many:

    #include 
    #include 
    
    int main(void) {
        int i;
        char bits[CHAR_BIT + 1];
        unsigned char value = 47;
    
        for (i = CHAR_BIT - 1; i >= 0; i -= 1) {
            bits[i] = '0' + (value & 0x01);
            value >>= 1;
        }
    
        bits[CHAR_BIT] = 0;
    
        puts(bits);
    
        return 0;
    }
    

提交回复
热议问题