+ 2
how to convert binary number to decimal number?
i face problem in dealing with point binary number to decimal number
7 Antworten
+ 9
int n;
string s = "";
cin >> n;
while(n != 0)
{
s = n % 2 + s;
n /= 2;
}
cout << s
+ 3
@Martin Taylor, yeah I wondered if it would be best. Fixed.
+ 1
In decimal (base 10), 1234 stands for
(1000 * 1) + (100 * 2) + (10 * 3) + (1 * 4), or
(10^3 * 1) + (10^2 * 2) + (10^1 * 3) + (10^0 * 4).
In binary (base 2), 1101 stands for
(8 * 1) + (4 * 1) + (2 * 0) + (1 * 1), or
(2^3 * 1) + (2^2 * 1) + (2^1 * 0) + (2^0 * 1).
which is 13. And that's how you do the conversion too. For each binary digit in your number starting from the right, you add 2^i to a total if it's 1 and 0 otherwise.
+ 1
3210 - bit order (index)
8420 - multiples of 2
1010 - binary number (10 in decimal)
Those are the steps (if you want to implement it by yourself):
1. You should store the binary number as String.
2. Declare an integer variable
3. Loop through all bits
On every iteration:
- get current bit and convert it to integer
- multiply the bit * 2^(bit index times)
- add the value to the integer variable
4. Print the integer variable.
Here is my Java implementation of above:
https://code.sololearn.com/ckuUA3RJhAqn/?ref=app
+ 1
You can test your implementation is working by comparing to...
#include <bitset>
cout << dec << 0b00101010 << endl; // binary to decimal
cout << bitset<8>(42) << endl; // 8 bits, 16 etc...
cout << hex << 42 << endl; // fyi
// 2a == 2*16¹ + 10*16° == 32 + 10 == 42