Skip to main content
3 of 3
added 258 characters in body
Duncan C
  • 5.7k
  • 3
  • 18
  • 30

You cannot do what you are trying to do. There is no direct correspondence between some number of bits and a decimal digit.

With hexadecimal, every 4 bits corresponds to exactly 1 hex digit. That is why hex is used for computers.

One hex digit represents exactly 4 bits. Every time you add another hex digit, you add 4 bits.

Two hex digits corresponds to exactly a byte. 00h to FFh represents a value from 0 to 255.

There is no such direct correspondence between binary and decimal. If you have 4 bits, it takes 1 or 2 decimal digits to represent it (0-15) If you have 8 bits, it takes 1, 2, or 3 decimal digits to represent it, but there are 3 digit decimal values (values > 255) that you can't represent with 8 bits.

Binary  Hex Decimal
0000    0   0
0001    1   1
0010    2   2
0011    3   3
0100    4   4
0101    5   5
0110    6   6
0111    7   7
1000    8   8
1001    9   9
1010    A   10
1011    B   11
1100    C   12
1101    D   13
1110    E   14
1111    F   15

You simply cannot convert a binary number to decimal using bit shifting and masking.

As @Kwasmich says in their answer, the closest you're likely to come would be to convert your binary value to BCD (Binary coded decimal) where each 4 bits holds a decimal digit. You could convert THAT to decimal character output using masking and shifting.

Duncan C
  • 5.7k
  • 3
  • 18
  • 30