Convert Binary/Hexadecimal Numbers

From HotDocs Wiki

Jump to: navigation, search
NOTE:

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

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

To convert binary numbers to hexadecimal, the computation begins by adding zeros to the beginning of the binary number until the number of digits is divisible by four. Then, each group of four digits is converted to a hexadecimal number (0–F) and concatenated to the end of the result.

To convert hexadecimal numbers to binary, the computation uses a WHILE loop to look at each digit in the hexadecimal number one at a time. A series of IF instructions then determine whether to append a 1 or 0 to the result, depending on which digit is found in the hexadecimal number. The result of the computation is a binary number with four times as many digits as the hexadecimal number.

Example

//Example 1: Convert a binary number to hexadecimal
""
SET Text Var TO Binary Number
 
WHILE REMAINDER( LENGTH( Text Var ), 4 ) > 0
  SET Text Var TO "0" + Text Var
END WHILE
 
WHILE LENGTH( Text Var ) > 0
  SET Num Var TO INTEGER( MID( Text Var, 1, 1 ) ) * 8
  SET Num Var TO Num Var + INTEGER( MID( Text Var, 2, 1 ) ) * 4
  SET Num Var TO Num Var + INTEGER( MID( Text Var, 3, 1 ) ) * 2
  SET Num Var TO Num Var + INTEGER( MID( Text Var, 4, 1 ) ) * 1
  IF Num Var < 10
    RESULT + FORMAT( Num Var, "9" )
  ELSE
    RESULT + FORMAT( Num Var - 9, "ABC" )
  END IF
  SET Text Var TO LAST( Text Var, LENGTH( Text Var ) - 4 )
END WHILE
 
//Example 2: Convert a hexadecimal number to binary.
""
SET Num Var TO 1
 
WHILE Num Var <= LENGTH( Hex Number )
  IF "89ABCDEF" CONTAINS MID( Hex Number, Num Var, 1 )
    RESULT + "1"
  ELSE
    RESULT + "0"
  END IF
  IF "4567CDEF" CONTAINS MID( Hex Number, Num Var, 1 )
    RESULT + "1"
  ELSE
    RESULT + "0"
  END IF
  IF "2367ABEF" CONTAINS MID( Hex Number, Num Var, 1 )
    RESULT + "1"
  ELSE
    RESULT + "0"
  END IF
  IF "13579BDF" CONTAINS MID( Hex Number, Num Var, 1 )
    RESULT + "1"
  ELSE
    RESULT + "0"
  END IF
  INCREMENT Num Var
END WHILE

Binary Number Any Text variable used to represent a binary number. A Text variable is used instead of a Number variable to avoid displaying commas when there are more than four digits in the answer.
Hex Number Any Text variable used to represent a hexadecimal number.
Text Var A temporary Text variable used in the computation. (See Create a Temporary Variable.)
Num Var A temporary Number variable used as a counter in the computation.