Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Binary to decimal conversion

1. ## Binary to decimal conversion

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??

west_dweller

• 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:

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

• 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

west_dweller79

• Here's a code to convert an any base string to an int:

Code:
```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;
}```

• 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

• 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 an article about it, if that helps.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•