...

View Full Version : Binary to decimal conversion



west_dweller79
02-18-2005, 07:30 PM
Dear all,

May i know how to convert binary to decimal using C++?? Also after converting to decimal, i need to display to the value in x.xx form.

Eg: 00000000 = 0(decimal) = 1.00volt
11111111 = 255(decimal) = 5.00volt

what i need to do is divide the decimal by 51 to get the value in volt. But how can i display the value in x.xx form??

Thanks in advance
west_dweller

Dr. Evil
02-18-2005, 07:34 PM
Just cycle through all the digits in the binary and add to the output number pow(2, current digit place) if that digit value is 1.

EDIT: As for printing with only 2 decimal places, just use the %f format specifier for printf(). For instance:



printf("%5.2f", (num / 51));

west_dweller79
02-19-2005, 01:23 AM
Sorry Dr Evil, don't get what you mean by cycle through all the digits in the binary and add to the output number pow(2, current digit place) if that digit value is 1.

If possible, can show me an example of how to do it

Thanks in advance
west_dweller79

Dr. Evil
02-19-2005, 09:12 AM
Here's a code to convert an any base string to an int:



unsigned long GetInt(char string[], unsigned long base)
{
unsigned long main, tmp;
int i, j;
char *pt1;

main = 0;
pt1 = &string[(strlen(string)-1)];
for(i=0, j=(strlen(string)-1); j>=0; j--, i++, pt1--)
{
if(isalpha(*pt1)) tmp = (toupper(*pt1) - 55);
else tmp = *pt1 - 48;
main += (tmp * (unsigned long)pow(base, i));
}

return main;
}

west_dweller79
02-19-2005, 12:56 PM
Sorry Dr Evil,

Refer to the 1st post that you reply, the solution that you tell me is in C and not C++. Can you please tell me how to display 2 decimal form using C++?

Thanks for you help with this and others
west_dweller

Dr. Evil
02-19-2005, 02:24 PM
Well you could use sprintf() then cout it from there, or use the setprecision() manipulator for cout. I'm afraid I'm not too well informed about usage of the latter, but here's (http://www.cee.hw.ac.uk/~pjbk/pathways/cpp1/node67.html) an article about it, if that helps.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum