Convert decimal number to character array representing hexadecimal number



hexStr = dec2hex(D) returns the hexadecimal, or base-16, representation of the number D. The output argument hexStr is a character vector that represents hexadecimal digits using the characters 0-9 and A-F.

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


hexStr = dec2hex(D,minDigits) returns a hexadecimal representation with no fewer than minDigits digits.


collapse all

Convert a decimal number to a character vector that represents its hexadecimal value.

D = 1023;
hexStr = dec2hex(D)
hexStr = 

Specify the number of hexadecimal digits that dec2hex returns. If you specify more digits than are required, then dec2hex pads the output with leading zeros.

D = 1023;
hexStr = dec2hex(D,6)
hexStr = 

If you specify fewer digits, then dec2hex still returns as many hexadecimal digits as required to represent the input number.

hexStr = dec2hex(D,1)
hexStr = 

Create a numeric array.

D = [1023 122 14];

To represent the elements of D as hexadecimal values, use the dec2hex function. Each row of hexStr corresponds to an element of D.

hexStr = dec2hex(D)
hexStr = 3x3 char array

The dec2hex function returns a character array padded with leading zeros. Starting in R2016b, the compose function is recommended for converting numeric arrays to hexadecimal representations. It returns a string array whose elements do not have leading zeros. To represent the elements of D as hexadecimal values, use either the %X or %x formatting operator.

hexStr = compose("%X",D)
hexStr = 1x3 string array
    "3FF"    "7A"    "E"

Input Arguments

collapse all

Input array, specified as an array of nonnegative numbers.

  • If D is an array of floating-point numbers, and any element of D has a fractional part, then dec2hex produces an error. For example, dec2hex converts 10 to 'A', but does not convert 10.5.

  • If D is a character or logical array, then dec2hex treats the elements of D as integers. However, dec2hex treats characters as their Unicode® values, so specifying D as a character array is not recommended.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char

Minimum number of digits in the output, specified as an integer.

  • If D can be represented with fewer than minDigits hexadecimal digits, then dec2hex pads the output with leading zeros.

  • If D is so large that it must be represented with more than minDigits digits, then dec2hex returns the output with as many digits as required.


  • If the input argument D has a value greater than the value returned by flintmax, then dec2hex might not return an exact representation.

Extended Capabilities

Introduced before R2006a