How to do hex-to-binary and binary-to-hex conversion?
Converting between hexadecimal (hex) and binary is a common task in programming and digital electronics, involving the translation of numbers between base 16 (hexadecimal) and base 2 (binary) systems. Each hex digit directly corresponds to a 4-bit binary digit, making the conversion straightforward.
Hexadecimal to Binary Conversion
To convert a hexadecimal number to binary:
- Replace each hex digit with its equivalent 4-bit binary value.
Hex to Binary Mapping:
- 0 → 0000
- 1 → 0001
- 2 → 0010
- 3 → 0011
- 4 → 0100
- 5 → 0101
- 6 → 0110
- 7 → 0111
- 8 → 1000
- 9 → 1001
- A → 1010
- B → 1011
- C → 1100
- D → 1101
- E → 1110
- F → 1111
Example: Convert Hex 1A3
to Binary
- 1 → 0001
- A → 1010
- 3 → 0011
Result:
1A3
in hex is000110100011
in binary.
Binary to Hexadecimal Conversion
To convert a binary number to hexadecimal:
- Split the binary number into groups of four bits. Start from the right (least significant bits). If the leftmost group has less than four bits, pad it with zeros.
- Replace each group of four bits with the corresponding hex digit.
Example: Convert Binary 110101110101
to Hex
- Split into groups:
1101 0111 0101
- Convert each group:
- 1101 → D
- 0111 → 7
- 0101 → 5
Result:
110101110101
in binary isD75
in hex.
Practical Methods for Conversion in Programming
In Python
Python provides built-in functions to handle these conversions:
hex()
converts an integer to a hexadecimal string.bin()
converts an integer to a binary string.- You can also use format strings or the
format()
function for more control over formatting.
# Hex to Binary hex_number = "1A3" binary_number = bin(int(hex_number, 16))[2:] # Convert hex to integer to binary print("Hex to Binary:", binary_number) # Binary to Hex binary_number = "110101110101" hex_number = hex(int(binary_number, 2))[2:] # Convert binary to integer to hex print("Binary to Hex:", hex_number.upper())
In JavaScript
JavaScript also provides methods for these conversions, utilizing the parseInt()
and toString()
methods.
// Hex to Binary const hexNumber = "1A3"; const binaryNumber = parseInt(hexNumber, 16).toString(2); console.log("Hex to Binary:", binaryNumber); // Binary to Hex const binaryNumber = "110101110101"; const hexNumber = parseInt(binaryNumber, 2).toString(16).toUpperCase(); console.log("Binary to Hex:", hexNumber);
Conclusion
Hex-to-binary and binary-to-hex conversions are straightforward due to the direct correspondence between hex digits and binary quartets. This makes the conversions easy to perform manually and programmatically. Such conversions are especially useful in fields like computer science, where binary and hexadecimal are used extensively to represent and manipulate data at low levels.
GET YOUR FREE
Coding Questions Catalog