HEX$ function

Purpose

Return a string that is the hexadecimal (base 16) representation of its argument.

Syntax

s$ = HEX$(numeric_expression [, digits])

Remarks

numeric_expression must be in the decimal range -2,147,483,648 to +4,294,967,295.  Any fractional part of numeric_expression is rounded before the string is created.

If digits is specified, the result string will be of length digitsdigits may be in the range 1 to 8.  If the value is shorter than digits, leading zeros are appended as needed.  If the value is longer than digits, the result will be truncated from the left as necessary.

Hexadecimal is a number system that uses base 16 rather than the base 10 used by the everyday decimal system.  In hexadecimal, the digits 0 to 9 represent the same numbers as in decimal, and the letters A to F represent the decimal values 10 to 15.  Hexadecimal notation is commonly used in programming because it is a convenient way of representing the binary bit patterns used internally by computers.  A single hex digit represents 1 nibble (4 bits), two hex digits represent one byte (8 bits), and so forth.

By convention, hex numbers are unsigned, since they represent bit patterns.  If you are not familiar with two's-complement arithmetic, the result of using HEX$ on a negative (signed) argument may surprise you.  See Numeric  Literals for more information on explicitly casting numeric literal values to specific data types and distinguishing between signed and unsigned values.  Also see the BIN$ function.

To display a Quad-integer in hex format, use the following technique:

DIM q AS QUAD, r AS STRING

q = &H0ABCEF0EE1234567F&&

r = HEX$(q / &H100000000, 8) & HEX$(q AND &HFFFFFFFF, 8)

Hexadecimal strings can be converted to numeric values with the VAL function by prefixing the hex string with "&H".  If the string has a leading zero, the result is always unsigned.  For example:

a$ = HEX$(65535)     ' a$ will contain "FFFF"

x& = VAL("&H" + a$)  ' Signed result (-1)

y& = VAL("&H0" + a$) ' Unsigned result (65535)

See also

BIN$, FORMAT$, OCT$, STR$, USING$, VAL

Example

DIM a AS DWORD, b AS STRING, c AS QUAD

a = &H0FFFFFFFF    ' Unsigned literal

b = HEX$(a)        ' "FFFFFFFF"

c = a              ' 4294967295

b = HEX$(c)        ' "FFFFFFFF"

c = VAL("&H" + b)  ' -1&& (signed conversion)

b = HEX$(c)        ' "FFFFFFFF"

c = VAL("&H0" + b) ' 4294967295&&

b = HEX$(c)        ' "FFFFFFFF"