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

Time:08-26

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"

CodePudding user response:

printf("%s%s",byte,byte2); //out: "hi" will not printf anything and is wrong. %s expects a pointer to char referencing null character terminated C string and you pass integers (char is an integer).

It has to be:printf("%c%c",byte,byte2);

int funny_function(const int *bit_array)
{
    int result = 0;
    for(int i = 0; i < 8; i  )
    {   
        result <<= 1;
        result  = !!bit_array[i];
    }
    return result;
}

in non zero bit_array element value is considered 1.

CodePudding user response:

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

int main() {
    // 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
    };

    // Simply use a loop, not a function
    for( int i = 0; i < sizeof bits/sizeof bits[0]; i   ) {
        char c = 0;

        // 7 bit values are 'accummulated' 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

EDIT:

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

int main() {
    // 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
    };

    // Simply use a loop, not a function
    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
  • Related