# Convert Binary/Decimal Numbers

### From HotDocs Wiki

You can use computations to convert binary numbers to decimal, 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 binary number.

To convert binary numbers to decimal, the computation result is initialized to zero, then each digit of the binary number is analyzed inside a WHILE loop. If HotDocs finds a 1, the power of 2 corresponding to that digit is added to the result. For example, for the binary number 0101, HotDocs finds the first 1 and adds 4 to the result. When HotDocs finds the second 1, it adds only 1 to the result, for a final answer of 5.

To convert decimal numbers to binary, the computation first determines how many digits are in the binary number by comparing the original decimal number to various powers of 2. (A decimal number less than 2(21) requires only one digit; greater than 2, but less than 4 (22) requires two digits, and so on.) Once the number of digits is determined, the binary 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".

## Example

//Example 1: Convert a binary number to decimal. 0 SET Num Var 1 TO 1 WHILE Num Var 1 <= LENGTH( Binary Number ) IF MID( Binary Number, Num Var 1, 1 ) = "1" RESULT + POWER( 2, LENGTH( Binary Number ) - Num Var 1 ) END IF INCREMENT Num Var 1 END WHILE //Example 2: Convert a decimal number to binary. "" SET Num Var 1 TO 0 SET Num Var 2 TO Decimal Number WHILE Num Var 2 >= POWER( 2, Num Var 1 ) INCREMENT Num Var 1 END WHILE DECREMENT Num Var 1 WHILE Num Var 1 >= 0 IF POWER( 2, Num Var 1 ) <= Num Var 2 RESULT + "1" SET Num Var 2 TO Num Var 2 - POWER( 2, Num Var 1 ) ELSE RESULT + "0" END IF DECREMENT Num Var 1 END WHILE IF RESULT = "" "0" END IF

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.) |

Decimal Number | Any Number variable used to represent a decimal (base 10) number. |

Num Var 1 | A temporary Number variable used in the computation. (See Create a Temporary Variable.) |

Num Var 2 | A temporary Number variable used in the computation. |