Conversion of Char to Binary in C

前端 未结 3 778
梦毁少年i
梦毁少年i 2020-11-28 10:37

I am trying to convert a character to its binary representation (so character --> ascii hex --> binary).

I know to do that I need to shift and AND. Howe

3条回答
  •  春和景丽
    2020-11-28 11:38

    unsigned char c;
    
    for( int i = 7; i >= 0; i-- ) {
        printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
    }
    
    printf("\n");
    

    Explanation:

    With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

    For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

提交回复
热议问题