Converting int array of 1's and 0's into true binary

Started by
14 comments, last by Matei 19 years, 7 months ago
Hi I currently have an array of 32 ints, that are either 1 or 0 and need to be able to convert them into a 32-bit interger with the same binary representation that is in the array. I have used bitwise operations to extract binary from ints and chars by doing a test like:

for (i = 0; i < 32; i++)
{
    if(num & 0x80)
        A = 1;
    else
        A = 0;
    num = num << 1;
}
representing the string in full binary and storing it in the array of ints, but i dont know how to go back the other way, converting an array like int A[4] = {0,0,1,0}; into the int 2. Can anyone help here? I am using C by the way.
Advertisement
I haven't tested this, but something like this could work I think:

It would be easier if you stored the numbers in there backwards, but whatever. Something like this perhaps?

unsigned char A[NumBits] = {1, 0, 0, 1, 0, 0, 1, 0};int Num = 0;for(int i = 0; i < 8; i++)    Num += (int)A << ((NumBits - 1) - i);
Thanks, I will give it a try. :)
by the way, that for loop should read:

for(int i = 0; i < NumBits; i++)

Right first time!

Works perfect man (well there was a couple of usual warnings :) ), thanks!
No problem, anytime. I'm glad it worked as I hadn't tested it or ever written anything like it before.

Anyways, what warnings did it give you?
Just a slight modification:

unsigned char A[NumBits] = {1, 0, 0, 1, 0, 0, 1, 0};int Num = 0;int bitMask = 1;for(int i = 0; i < NumBits; i++){    bitMask <<= 1;    if(A) Num |= bitMask;}

It's the same but optimized, I think.
unsigned char A[NumBits] = {1, 0, 0, 1, 0, 0, 1, 0};int Num = 0;for(int i = 0; i < NumBits; i++) {    Num <<= 1;    Num |= A; // loses error checking, but should be even faster    // versus "if (A) Num |= 1;"}
Unfortunately not. In that example you are just repeatedly setting the least significant bit.
Quote:Original post by MrEvil
Unfortunately not. In that example you are just repeatedly setting the least significant bit.


But he's shifting 'num' up by one space every turn, so the bits move from the least significant spot up. Like a printer- the ink thingy stays still but the paper moves.

This topic is closed to new replies.

Advertisement