Home > Software engineering >  Convert two's complement binary to decimal
Convert two's complement binary to decimal

Time:11-03

So i have to convert two's complement binary to decimal in C by first inserting the number of bits user wants to use 1 by one for example: Bits: 4

Insert the bit in position 3: 1

Insert the bit in position 2: 0

Insert the bit in position 1: 0

Insert the bit in position 0: 0

I have done the code for this using an array and then using for to store a[i]. I'm stuck and i dont know what to do to convert it to decimal. I would appreciate any help thanks.

int main() {
int n;
cout << "Bits: " << endl;
cin >> n;

while (n < 2) {
    cout << "Error! " << endl;
    cout << "Bits: " << endl;
    cin >> n;
}
int a[10000];

for (int i = n; i > 0; i--) {
    cout << "Insert the bit in position " << i - 1 << ": " << endl;
    cin >> a[i];
    while (a[i] != 0 && a[i] != 1) {
        cout << "Error! " << endl;
        cout << "Insert the bit in position " << i - 1 << ": " << endl;
        cin >> a[i];
    }
}

int choice;

cout << "Operation: " << endl;
cout << "      0 - Print binary: " << endl;
cout << "      1 - Convert in decimal: " << endl;


cout << "Choice: ";
cin >> choice;
cout << endl;

switch (choice) {
    case 0:
        cout << "Binary number: ";
        for (int i = n; i > 0; i--)
            cout << a[i];
        cout << endl;
        break;

CodePudding user response:

To convert your a array from a list of 0 and 1 integers to unsigned decimal:

unsigned long sum = 0;
for (int i = 0; i < n; i  )
{
    sum = sum*2   a[i];
}

If you are expected to interpret these bits as signed values such that 11001100 would be interpreted as -52 instead of 204. You will need to do the following:

  • First check if a[0] == 0. If it is, then all you need to do is the summation loop above and you are done. You can print sum as is.
  • Otherwise, if a[1] == 1, then that implies this is a negative number and we need to do 2's complement to interpret it. Continue with the following:
  • Flip all the values in a (0's become 1s and 1s become 0's) from index 0 through n-1.
  • Arithmetically "add 1". You just need to reflip the bits in a starting at a[n-1] and work your way from right to left. Stop after flipping a 0 to 1.
  • Then apply the summation loop above to get the absolute value of the number. Then print a negative sign followed by the postive value computed for sum. You might be tempted to say, long negativeSum = -sum and just print that. And that will work most of the time, except there's an edge case.

I'll leave the actual coding as an exercise for you.

  •  Tags:  
  • c
  • Related