How to convert bit string into integer?

2.4k Views Asked by At

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.

1

There are 1 best solutions below

6
On BEST ANSWER

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.