decimal hex
Page 1 of 1

Author:  fredster [ Sat Mar 12, 2011 11:19 am ]
Post subject:  decimal hex

Hi! I have to convert decimal to hexadecimal, but there's also a fraction part (e.g. 5.3232), which I suppose I have to convert to hex as well. I am stuck with converting the fraction part. I thought of multiplying the fraction part by 16 method, but then I don't have a decimal point! I hope I can get some tips on how to do this.

Author:  clive [ Sat Mar 12, 2011 12:16 pm ]
Post subject: 

Well this really depends on the question being asked and the expectation of the lecturer.

One approach would be to have a 32-bit number storing a 16.16 fixed point representation. ie the upper 16-bits are the integer portion, the lower 16-bits fractional.

For example


Read this in as a whole, taking note of the decimal place
53232 = 0x0000CFF0

There are 4 decimal places, so the number must ultimately be divided by 10000 (0x2710), but

First you shift the number 16-bits left, or *65536
0x0000CFF0 * 65536 = 0xCFF00000

Now we divide that by 10000
0xCFF00000 / 10000 = 0x000552BD

Note the high-order sixteen bits are 0x0005 (5), the integer portion.

To decode the fractional portion, remove the high-order word, and multiply by 10
0x000052BD * 10 = 0x00033B62, so 3
0x00003B62 * 10 = 0x000251D4, so 2
0x000051D4 * 10 = 0x00033248, so 3
0x00003248 * 10 = 0x0001F6D0, so 1
0x0000F6D0 * 10 = 0x0009A420, so 9

Making the decimal portion .32319, the imprecision due to the limited 16-bits available, and the limit of binary fractions to represent certain values. ie Like base 10 representing 1/3

You could address this by only printing 4 digits and rounding, but this might be beyond the scope of the exercise.

The precision could be improved by using a 4.28 fixed point representation (4-bit integer, 28-bit fractional) for example, or 8.24, depending on how large you expect your integer portion to be, or if you need to handle signing.

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group