Jump to content
  • Advertisement
Sign in to follow this  
Mr Lane

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

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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);

Share this post


Link to post
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!