简体   繁体   中英

C - Printing binary for a given character

I am learning C and part of my exercise is dealing with bitwise operators. I am trying to create a function that prints out a 2's complement for a char input.

Here is what I have so far:

#include <stdio.h>
#include <stdlib.h>

void  find_binary(char ch) {

        long bit_index = 0;
        unsigned long sz = sizeof(ch)*8-1;
        for (bit_index = 0; bit_index <= sz; ++bit_index) {
                int bit = (1 << bit_index) & ch;
                printf("%d", bit);
        }
        printf("\n");
}

Here is the output: 0008032640 when I input 'h' .

Why is this printing integers other than 0 and 1?

The expression

int bit = (1 << bit_index) & ch;

produces a zero or a power of two with the corresponding bit set. To bring it into the 0..1 range, either shift ch right and mask with 1 , or convert your expression as follows:

int bit = ((1 << bit_index) & ch) != 0;

Try the following code

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

void  find_binary( char ch ) 
{
    for ( int i = CHAR_BIT; i != 0; )
    {
        int bit = ( 1 << --i & ch ) != 0;
        printf( "%d", bit );
    }
}

int main( void )
{
    find_binary( 'A' );

    return 0;
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM