See also:
Base conversion of positional number systems for other conversion functions.
Download
hex2dec2.m
Hexadecimal numbers
"Normal"
decimal numbers use a base 10 system, most likely because humans have 10 fingers.
Hexidecimal is a base 16 number system (presumably because computer programmers have 16 fingers), so whereas the decimal number system has 10 numbers (
0-9), hexadecimal has 16 (
0-9, and
A,
B,
C,
D,
E and
F).
Like decimal (and binary) hexidecimal is a positional number system, where a numbers position determines its value. This means that calculating the value of a hexidecimal number is
exactly the same process as calculating the value of a decimal number. Observe:
Consider the decimal value
2345. The value is obvious. It's
2345. But it can be broken down into the sum of
2000 + 300 + 40 + 5. And each of these values depends on the number of zeros, which is determined by position. Positions start from 0 and count up right to left, so the 2 in
2345 is in position 3, the 3 is in position 2, the 4 is in position 1 and the 5 in position 0. Mathematically this means the value of the 2 is
2*10^3 = 2000, of the 3 is
3*10^2 = 300, and so on. Overall the total value of the number is:
(2*10^3) + (3*10^2) + (4*10^1) + (5*10^0) = 2345.
For hexadecimal numbers, exactly the same process applies, except using a base of 16. The only caveat being that the letters, if there are any, need to be replaced with their equivalent decimal numbers first. So what's the value of the hex number
2345 (notice that for hex values without letters, it's not immediately obvious it's a hex number - so it should be written as either
0x2345 or
234516 to avoid this ambiguity).
0x2345 (hex) = (2*16^3) + (3*16^2) + (4*16^1) + (5*16^0) = 9026 (decimal).
If there are letters in the hex number, for example:
0xF34B, these need to be converted to decimal values first, which is simple:
A=
10,
B=
11,
C=
12,
D=
13,
E=
14,
F=
15. So,
0xF34B = (F*16^3) + (3*16^2) + (4*16^1) + (B*16^0) , or
0xF34B = (15*16^3) + (3*16^2) + (4*16^1) + (11*16^0) = 62283
This process is simple to implement in Matlab, and is very similar to the process to convert decimal values to binary (see
dec2bin2). The only complication is the handling of the letters; in Matlab hexadecimal numbers must be strings, because they contain letters. This means that isn't not possible to directly perform mathematical operations on them, such as the above conversion, but Matlab has a number of convenient features for dealing with strings that we'll exploit.
Overall, this function will convert the hexadecimal input to decimal numbers, work out the value of each based on its position, the calculate the sum of all these values to give the final decimal value. It provides an alternative to Matlab's
hex2dec function.