Converting characters to hexadecimal

A hexadecimal number is one with a base of 16. So instead of decimal which goes from 0..9, hexadecimal is 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F. So how to convert a character to hexadecimal? Let’s take the character ‘Z‘ as an example. Its hexadecimal value is 5A, but how do we calculate that? Here’s the algorithm:

  1. Take a character, and convert it to its ASCII value. e.g. Z=90
  2. Divide by 16. This is the first part of the hex. 90/16 = 5.
  3. The remainder is the second part of the hex. mod(90,16) = 10
  4. The hex value for 10 is A, so the hex for Z is 5A.

Now this could be stored in a two character string as 5A, or in a two integer array as 5 and 10.

To convert a whole word, the string is converted one character at a time. Here is an example with the word bubble = 6 characters

  1. CHAR  =   B   u   b   b   l   e
    ASCII =   66  117 98  98  108 101
    HEX   =   42  75  62  62  6c  65
    

Now the hex numbers could be stored in two types of array, as characters, or integers. The most common way of storing these are as an integer array, where each component of the hex number is stored in a separate element. Here is an example in Fortran:

  1. integer, dimension(0:31) :: h
    h = (/ 4, 2, 7, 5, 6, 2, 6, 2, 6, 12, 6, 5 /)

2 thoughts on “Converting characters to hexadecimal

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.