HEX$ function

Purpose: HEX$ converts an integer to a hexadecimal string.


 Syntax:

 RetStr$ = HEX$(Number%)

 Parameters:

  • RetStr$ Hexadecimal string of Number%.
  • Number% Integer to be converted to hexadecimal string.

Example 1 :


 A$ = HEX$(65535)

Result:

A$ will equal "FFFF".

Example 2:


 'This example will print the hexadecimal
 'codes for each of the characters in A$

 DIM A$
 DIM i%

 A$ = "abcde"

 FOR i%= 1 TO LEN(A$)
   PRINT HEX$(ASC(MID$(A$, i%, 1))) & " ";
 NEXT i%

Result:

61 62 63 64 65

HEX2DEC function

Purpose: HEX2DEC takes a string argument representing a hexadecimal number and returns a 32 bit decimal integer. It is the programmer's responsibility to trap and remove all non-hex characters from the input string, otherwise the function will certainly yield incorrect results.


 Syntax:

 RetVal% = HEX2DEC(HexString$)

 Parameters:

  • RetVal$ Returned 32 bit decimal integer value of HexString$.
  • HexString$ Hexadecimal string to be converted to integer. The case-insensitive argument may take the following forms:
    • "&Hffff" Hex string prepended with BASIC designation "&H" or "&h"
    • "0xffff" Hex string prepended with C designation "0x" or "0X"
    • "ffff" Hex string

More hexadecimal to decimal conversion methods

In BCX the syntax to convert from hexadecimal to decimal is different from that used in QBASIC. In BCX the hexadecimal string is preceded with 0x (zero x) not QBASIC syntax &H.

Example 1:


 DIM aDecimal%

 aDecimal% = 0x1E240

 PRINT aDecimal%

Result:

aDecimal% will equal 123456

Example 2:

Here is a short program that uses a hexadecimal to decimal conversion function written as a BCX macro utilizing the C function strtol. This example shows how to convert a hexadecimal string variable to a decimal.


 CONST HEXTODEC%(a) = strtol(a,NULL,16)

 DIM aDecimal%
 DIM aHexMainStr$
 aHexMainStr$ = "1E240"
 aDecimal% = HEXTODEC(aHexMainStr$)
 PRINT aDecimal%

Result:

aDecimal% will equal 123456

Example 3:

BCX's HEX2DEC will only handle 32 bits "0xFFFFFFFF". Here is a little routine to extend it to 64 bits.

 
 DIM RV#
 
 RV# = Hx2Dec("0x0861c46800")
 PRINT USING$("###,###,###,###", RV)
 
 PAUSE
 
 FUNCTION Hx2Dec(h$) AS ULONGLONG
 
   DIM RAW hx$
   DIM RAW value AS ULONGLONG
 
   hx$ = LPAD$(REMAIN$(h$,"x"), 16, ASC("0"))
 
   value = ((ULONGLONG)HEX2DEC(LEFT$(hx$,8)) << 32)
   value|= (ULONG)HEX2DEC(RIGHT$(hx$,8))
 
   FUNCTION = value
 END FUNCTION