Andrew Masden
Andrew Masden

Reputation: 3

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?

Upvotes: 0

Views: 450

Answers (2)

Lundin
Lundin

Reputation: 213799

I have converted these binary numbers into the integer array

Why? That's not a helpful format for the computer, it's just a superfluous middle step. Get rid of that, it isn't needed.


How to store values in an integer depends on endianess, What is CPU endianness? If we don't understand this first, then no can do.

Now what you call "literal binary value" is actually the big endian representation, with the first character stored at the most significant address. We can make endianess portable code by using bit shifts to always shift the first letter to the ms byte:

#include <stdio.h>
#include <stdint.h>

int main (void)
{
  char quadgram[4] = {'T','I','O','N'};
  uint32_t val;

  val = (uint32_t)quadgram[0] << 24 |
        (uint32_t)quadgram[1] << 16 |
        (uint32_t)quadgram[2] <<  8 |
        (uint32_t)quadgram[3] <<  0 ;

  printf("%d\n", val);
}

Upvotes: 0

Locke
Locke

Reputation: 374

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
}

Upvotes: 1

Related Questions