View Single Post
 
[C++]Binary -> Decimal
Reply
Posted 2004-01-30, 07:46 PM
Another program I wrote to help someone new...
It was quickly written

Code:
#include "stdafx.h"
#include <windows.h>
#include <iostream.h>

int toPower2(int value){
	int rtnvle = 1;
	if(value > 1)
    for(int i=2;i<=value;i++){
        rtnvle *= 2;
	}
	return rtnvle;
}

int main(int argc, char* argv[])
{
	char binary_value[16];
	int  decimal = 0;

    cout<<"Type in a binary value 16 max(remember binary is right to left): ";
	cin>>binary_value;
	
    for(int i=strlen(binary_value) -1;i >= 0;i--){
		if(binary_value[i] == '1'){
			decimal += toPower2(strlen(binary_value) - i);
		} 
	     else if(binary_value[i] != '0')
		         return 0;
	}

    cout<<decimal<<endl;
	return 0;
}
PS: I wanted to use pointers but that would of been to complex for the person I was teaching
Old
Profile PM WWW Search
Acer enjoys the static noises of ten television sets simultaneously tuned to 412.84 MHzAcer enjoys the static noises of ten television sets simultaneously tuned to 412.84 MHz
 
 
Acer