-1

Is there any way to convert a 2'scomplement bit string into a integer? I think it's easy enough for positive numbers, but as for negative numbers I'm a little confused.

#include <stdio.h>
int bits2Integer(char bitString[]){
     int value = 1;
     int power = 1;
     int constantIncrement = 2;
     if(bitString[0] == 0) {
          for(int i = 32; i >= 0; i--){
               if(bitString[i] == 1){
                    value = value + power;
                    power = power * constantIncrement;
               }
               else {
                    power = power * constantIncrement;
               }
     }
}

Oh, and I don't want to use any other library/resource other than stdio.h.

7
  • 3
    "I don't know if it works" - why don't you try testing it? Commented Jun 7, 2015 at 17:18
  • 1
    you made it and you don't know if it works ? Commented Jun 7, 2015 at 17:25
  • 0)int value = 1; --> int value = 0; 1) int i = 32; --> int i = 31; 2) bitString[i] == 1 --> bitString[i] == '1' 3) return value; add to last Commented Jun 7, 2015 at 17:41
  • I didn't see all the comments before I refreshed the page, sorry guys Commented Jun 7, 2015 at 17:51
  • @OliverCharlesworth I'm running on Windows, so I'm only running the codes through my brain. Sorry for the confusion. If you don't mind me asking, is there a functional C compiler for Windows? Commented Jun 7, 2015 at 17:55

1 Answer 1

2

This seems to be the best way

#include <stdio.h>
int bits2Integer(char bitString[]){
     int ret = 0;
     for(int i = 0; i < 32; i++)
          if(bitString[i] == '1')
            ret |= 1 << (31-i);

     return ret;
}

Bitwise operations rule the world :)

Remember that you can't have 33 bits.

Sign up to request clarification or add additional context in comments.

7 Comments

Hi, that would work perfectly! Does that also work for 2's complement too? I'm very new to C, so still learning all the bit manipulations and tricks.
@Leon The question is what you mean by the two's complement. If you have a negative number in form of bits written in a string, and you'd like to turn it into an integer, then yes, this will work for this too. If I've answered your question, please, tick the green "OK" on the left side to accept it :)
@BLUEPIXY I understand the logic though, I'll write it in my own version :)
@BLUEPIXY can you support your statement? It works perfectly, tested with IdeOne.com.
0) { remove or add } 1) 1 << i should be 1 << (31-i)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.