View Single Post
  #6 (permalink)  
Old March 15th, 2009, 11:34 AM
bert bert is offline
Registered User
 
Join Date: Mar 2009
Posts: 7
Thanks: 0
Thanked 1 Time in 1 Post
Default

Hope this helps
Code:
#include <iostream>
#include <cassert>
#include <iomanip>
#include <cstring>
using std::setw;
using std::cout;
using std::endl;

const int BITS = 8;

int convert(char binary[]) {
    int power = 128;
    int sum = 0;
    assert(strlen(binary) == 8);

    for ( int i=0; i<BITS; ++i) {
        if ( i==0 && binary[i]!='0') {
            sum = -128;
        }
        else {
            sum += (binary[i]-'0')*power;
        }
        power /= 2;
    }
    return sum;
}
int main()
{
    char bin1[BITS+1] = "00000011";
    cout <<"Binary: "<< bin1 <<endl<<"Dec:    "<< setw(8) << convert(bin1) << endl<< endl;
    
    char bin2[BITS+1] = "10000000";
    cout <<"Binary: "<< bin2 <<endl<<"Dec:    "<< setw(8) << convert(bin2) << endl<< endl;

    char bin3[BITS+1] = "01111111";
    cout <<"Binary: "<< bin3 <<endl<<"Dec:    "<< setw(8) << convert(bin3) << endl<< endl;

return 0
}
Reply With Quote
The Following User Says Thank You to bert For This Useful Post:
RustyOnRampage (February 25th, 2013)