Convert Decimal/Hexadecimal Numbers

From HotDocs Wiki

Jump to: navigation, search

You can use computations to convert decimal numbers to hexadecimal, and vice versa. For example, if a user enters a decimal number in an interview, you can use a computation to merge the answer in the assembled document as a hexadecimal number.

To convert decimal numbers to hexadecimal, the computation first determines how many digits are in the hexadecimal number by comparing the original decimal number to various powers of 16. (A decimal number less than 16 (161) requires only one digit; greater than 16, but less than 256 (162) requires two digits, and so on.) Once the number of digits is determined, the hexadecimal number is added to the result, one digit at a time. At the end of the computation, if the result is still empty, the computation result is "0".

To convert hexadecimal numbers to decimal, the computation examines each digit in the hexadecimal number, one at a time, and multiplies it by the corresponding power of 16. Each of these results are added to return the sum, which is the number converted to a decimal (base 10) number.

CAUTION: These computations use the WHILE, INCREMENT, and DECREMENT instructions, which work only in HotDocs 6.2 and higher.

Example

//Example 1: Convert a decimal number to hexadecimal.
""
SET Num Var 1 TO 0
SET Num Var 2 TO Decimal Number
 
WHILE Num Var 2 >= POWER( 16, Num Var 1 )
  INCREMENT Num Var 1
END WHILE
 
DECREMENT Num Var 1
 
WHILE Num Var 1 >= 0
  IF POWER( 16, Num Var 1 ) <= Num Var 2
    IF TRUNCATE( Num Var 2 / POWER( 16, Num Var 1 ), 0 ) < 10
      RESULT + FORMAT( TRUNCATE( Num Var 2 / POWER( 16, Num Var 1 ), 0 ), "9" )
    ELSE
      RESULT + FORMAT( TRUNCATE( Num Var 2 / POWER( 16, Num Var 1 ), 0 ) - 9, "ABC" )
    END IF
    SET Num Var 2 TO REMAINDER( Num Var 2, POWER( 16, Num Var 1 ) )
  ELSE
    RESULT + "0"
  END IF
  DECREMENT Num Var 1
END WHILE
 
IF RESULT = ""
  "0"
END IF
 
//Example 2: Convert a hexadecimal number to decimal.
0
SET Num Var 1 TO 1
SET Num Var 2 TO LENGTH( Hex Number ) - 1
WHILE Num Var 2 >= 0
  IF MID( Hex Number, Num Var 1, 1 ) = "A"
    RESULT + 10 * POWER( 16, Num Var 2 )
  ELSE IF MID( Hex Number, Num Var 1, 1 ) = "B"
    RESULT + 11 * POWER( 16, Num Var 2 )
  ELSE IF MID( Hex Number, Num Var 1, 1 ) = "C"
    RESULT + 12 * POWER( 16, Num Var 2 )
  ELSE IF MID( Hex Number, Num Var 1, 1 ) = "D"
    RESULT + 13 * POWER( 16, Num Var 2 )
  ELSE IF MID( Hex Number, Num Var 1, 1 ) = "E"
    RESULT + 14 * POWER( 16, Num Var 2 )
  ELSE IF MID( Hex Number, Num Var 1, 1 ) = "F"
    RESULT + 15 * POWER( 16, Num Var 2 )
  ELSE
    RESULT + INTEGER(MID( Hex Number, Num Var 1, 1 ) ) * POWER( 16, Num Var 2 )
  END IF
  INCREMENT Num Var 1
  DECREMENT Num Var 2
END WHILE