Main Content

num2hex

Convert single- and double-precision numbers to IEEE hexadecimal format

Description

example

hexStr = num2hex(X) returns a representation of X in IEEE® format using hexadecimal digits.

  • If X is a double-precision number, then hexStr has 16 characters.

  • If X is a single-precision number, then hexStr has 8 characters.

  • If X is a vector, matrix, or multidimensional array, then hexStr is a two-dimensional character array. Each row of hexStr represents an element of X.

Unlike the dec2hex function, num2hex can convert floating-point values with fractional parts. Also, num2hex handles NaN and Inf values and denormal numbers correctly.

The format produced by num2hex is identical to the one produced by the format hex command.

Examples

collapse all

Create a number and represent it in its IEEE® format using hexadecimal digits. X is a double-precision number and has a fractional part.

X = 3.1416;
hexStr = num2hex(X)
hexStr = 
'400921ff2e48e8a7'

Since hexStr is in IEEE format, it also represents the fractional part of X. You can convert hexStr back to a number using the hex2num function.

hex2num(hexStr)
ans = 3.1416

Create a single-precision number.

X = single(2.7182818)
X = single
    2.7183

Convert X. The num2hex function represents a single-precision number using only eight hexadecimal digits.

hexStr = num2hex(X)
hexStr = 
'402df854'

Convert a negative number and represent it in IEEE® format.

num2hex(-1)
ans = 
'bff0000000000000'

Convert NaN.

num2hex(NaN)
ans = 
'fff8000000000000'

Convert Inf.

num2hex(Inf)
ans = 
'7ff0000000000000'

Create a numeric array.

X = [3.1416 1.37e-5 1023.92];

Convert the elements of X. The num2hex function returns a character array that represents these values.

hexStr = num2hex(X)
hexStr = 3x16 char array
    '400921ff2e48e8a7'
    '3eecbb21a99df39b'
    '408fff5c28f5c28f'

Input Arguments

collapse all

Input array, specified as a numeric array.

Data Types: single | double

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Version History

Introduced before R2006a