Search code examples
arrayscbinaryrepresentation

How to convert an int array into a single int c


I have a integer array, int KEY[32], that stores the binary representation of a four letter quadgram, e.g.:

char quadgram[4] = {'T','I','O','N'};

Where the binary representations of the characters are:T => 01010100, I => 01001001, O => 01001111, N => 01001110. I have converted these binary numbers into the integer array:

KEY[32] = 01010100010010010100111101001110;

Now I need to convert this KEY into its literal binary value, i,e:

int KEY_BIN = 1414090574; // in decimal.

How would I accomplish converting KEY into KEY_BIN?


Solution

  • Given the array of integers, you can loop over them, bitshift the number by the appropriate numbers of bits, and then bitwise OR it with your result value. You'll want KEY to be an array of unsigned ints in order to have well-defined bitshift behaviour.

    A working example:

    #include <stdio.h>
    
    int main() {
       unsigned int KEY[32] = {0, 1, 0, 1, 0, 1, 0, 0, 0, 
                               1, 0, 0, 1, 0, 0, 1, 0, 1, 
                               0, 0, 1, 1, 1, 1, 0, 1, 0, 
                               0, 1, 1, 1, 0 };
       unsigned int result = 0;
       for ( unsigned int i = 0; i < 32; ++i ) {
          unsigned int shiftAmount = 32 - i - 1;
          unsigned int shifted = KEY[i] << shiftAmount;
          result |= shifted;
       }
    
       printf( "%u\n", result ); // Prints 1414090574
    }