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

This topic is 5214 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites
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);

##### Share on other sites
Thanks, I will give it a try. :)

##### Share on other sites
by the way, that for loop should read:

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

##### Share on other sites
Right first time!

Works perfect man (well there was a couple of usual warnings :) ), thanks!

##### Share on other sites
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?

##### Share on other sites
Just a slight modification:

unsigned char A[NumBits] = {1, 0, 0, 1, 0, 0, 1, 0};
int Num = 0;

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

It's the same but optimized, I think.

##### Share on other sites

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;"
}

##### Share on other sites
Unfortunately not. In that example you are just repeatedly setting the least significant bit.

##### Share on other sites
Quote:
 Original post by MrEvilUnfortunately 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.

1. 1
2. 2
Rutin
21
3. 3
4. 4
A4L
15
5. 5
khawk
14

• 13
• 26
• 10
• 11
• 44
• ### Forum Statistics

• Total Topics
633742
• Total Posts
3013636
×