Converting a decimal to a hexadecimal number

亡梦爱人 提交于 2019-12-04 11:48:52

In an ASCII environment, 55 is equal to 'A' - 10. This means that adding 55 is the same as subtracting 10 and adding 'A'.

In ASCII, the values of 'A' through 'Z' are adjacent and sequential, so this will map 10 to 'A', 11 to 'B' and so on.

For values of temp less than 10, the appropriate ASCII code is 48 + temp:

0 => 48 + 0 => '0'
1 => 48 + 1 => '1'
2 => 48 + 2 => '2'
3 => 48 + 3 => '3'
4 => 48 + 4 => '4'
5 => 48 + 5 => '5'
6 => 48 + 6 => '6'
7 => 48 + 7 => '7'
8 => 48 + 8 => '8'
9 => 48 + 9 => '9'

For values 10 or greater, the appropriate letter is 55 + temp:

10 => 55 + 10 => 'A'
11 => 55 + 11 => 'B'
12 => 55 + 12 => 'C'
13 => 55 + 13 => 'D'
14 => 55 + 14 => 'E'
15 => 55 + 15 => 'F'

Because of the ASCII encoding of characters in C. When the remainder (temp) is less than ten, the digit in the hexadecimal is also in the range of 0 to 9. The characters '0' to '9' are on the ASCII range of 48 to 57.

When the remainder is more than 10 (and always less than 15, due to the remainder operation %) the hexadecimal digit is in the range A to F, which in ASCII is in the range of 65 to 70. So temp + 55 is a number from 65 to 70 and thus gives a character in the range of 'A' to 'F'.

It is more common to use a string char[] digits = "0123456789ABCDEF"; and use the remainder as an index in this string. The method in your question (probably) works as well though.

Hexadecimal number is a number represented using 16 symbols which are 0 -9 numbers and A – F alphabets. Procedure to write a c program to convert decimal number to hexadecimal is: Divide the decimal number with 16 at each step and take remainders

Here for remainders 0 – 9 numbers are used and then to represent 10 to 15 numbers we use alphabets A, B, C, D, E, F . Now combine all remainders serially from down to up i.e A This is hexadecimal number of 10 (decimal )

eg To convert decimal number 10 to hexadecimal

16 | 10 | 0 – A

Now combine all remainders serially from down to up i.e A . This is hexadecimal number of 10 (decimal )

Program Logic: Enter decimal number n, divide n by 16 ( since hexadecimal ) and save remainder in array and quotient in n repeat until n is greater than zero

view program at: http://www.programmingsimplysolved.com/c-programs/c-program-to-convert-decimal-number-to-hexadecimal-using-functions/

contributed by: www.programmingsimplysolved.com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!