Search code examples
cbytebit

How would I make a integer array (of 0's and 1's) into a char?


What would be a way to convert an array like this

int bit_array[8] = {0,0,0,0,0,0,0,0};

into a char? (assuming bit_array is in ascii or similar)

for example an end result would preferably be like this:

int bit_array[8] = {0,1,1,0,1,0,0,0}; // h
int bit_array2[8] = {0,1,1,0,1,0,0,1}; // i
char byte;
char byte2;
byte = funny_function(bit_array);
byte2 = funny_function(bit_array2);
printf("%s%s",byte,byte2); //out: "hi"

Solution

  • Without using a function call, you can do this with a loop in the body of main().

    int main( void ) {
        // Only need 7 'bits'.
        // Let compiler measure size.
        // Use 1 byte 'char' instead of multibyte 'int'
        char bits[][7] = {
            {1,1,0,1,0,0,0}, // h
            {1,1,0,0,1,0,1}, // e
            {1,1,0,1,1,0,0}, // l
            {1,1,0,1,1,0,0}, // l
            {1,1,0,1,1,1,1}, // o
        };
    
        // for each character row of array
        // Simply use a loop, not a function
        for( int i = 0; i < sizeof bits/sizeof bits[0]; i++ ) {
            char c = 0;
    
            // for each bit of each character
            // 7 bit values are 'accumulated' into 'c'...
            for( int ii = 0; ii < sizeof bits[0]/sizeof bits[0][0]; ii++ )
                c = (char)( (c << 1) | bits[i][ii] ); // Magic happens here
    
            putchar( c );
        }
        putchar( '\n' );
    
        return 0;
    }
    

    (Friendly) output:

    hello
    

    As above, an alternative version if output limited to only single case alphabet (fewer bits).

    int main( void ) {
        // Only need 5 'bits'.
        char low_bits[][5] = {
            {0,1,0,0,0}, // h
            {0,0,1,0,1}, // e
            {0,1,1,0,0}, // l
            {0,1,1,0,0}, // l
            {0,1,1,1,1}, // o
        };
    
        for( int i = 0; i < sizeof low_bits/sizeof low_bits[0]; i++ ) {
            char *cp = low_bits[i]; // for clarity (brevity)
    
            // Magic happens here...
            char c = (char)(cp[0]<<4 | cp[1]<<3 | cp[2]<<2 | cp[3]<<1 | cp[4] );
    
            putchar( c | 0x40); // uppercase. use 0x60 for all lowercase.
        }
        putchar( '\n' );
    
        return 0;
    }
    

    (Not so friendly) output (unless calling to distant person):

    HELLO