Converting from hexadecimal to binary is a common task. There have been several approaches to performing this conversion in Python.
In computer science, two significant number systems are used to represent data in digital format: hexadecimal and binary. Binary is a base-2 number system that uses only the digits 0 and 1, whereas hexadecimal is a base-16 number system that uses 16 digits.
In this article, we’ll look at four Python conversion methods for hexadecimal to binary and compare their benefits and drawbacks. We will also suggest the most appropriate method based on the standards of simplicity, readability, and effectiveness.
Why is there a need to convert hexadecimal to binary in python?
Hexadecimal to binary conversions are occasionally required in Python programming for a number of reasons.
- Hexadecimal and binary representations are employed in scientific and technical applications to represent values in a condensed manner, and conversion is required to carry out calculations.
- To interface with some embedded devices and microcontrollers that employ hexadecimal for programming, binary conversion is required.
- Working with digital audio and video signals, which are frequently represented in hexadecimal format, necessitates the conversion of hexadecimal to binary.
- Hexadecimal codes are frequently used to identify the problems or system states while troubleshooting hardware or software; translating these codes to binary can aid in figuring out the root of the problem.
- When dealing with low-level programming activities like working with memory addresses and device drivers, converting hexadecimal to binary is crucial.
- In order to manage the colour values, hexadecimal integers used to represent colours in web development must be converted to binary.
- Hexadecimal and binary formats are commonly used in cryptographic techniques, and conversions between the two are necessary for their implementation.
- For convenience of reading, binary data is frequently transferred across networks in hexadecimal format conversion is required to operate this data in binary form.
- Working with file formats that employ hexadecimal codes to represent characters or symbols makes converting hexadecimal to binary crucial.
In conclusion, as computers work with binary data and frequently need such data to be in binary form for processing, there is a requirement for converting hexadecimal to binary in Python. Memory locations, file formats, and digital signals are all represented in hexadecimal, a more understandable format that is frequently used in programming. Cryptographic algorithms must be converted between these two number systems in order to be put into practice.
For programmers dealing with low-level programming, networking, or encryption, knowing how to convert hexadecimal to binary in Python is an important ability. By learning this ability, programmers may more effectively deal with complicated systems and modify data in a variety of formats.
Approaches:
- Using the bin() and int() function.
- Using the format() function.
- Using a loop and bitwise operators.
- Using a dictionary lookup with bitwise operators.
Approach 1 : Using the bin() and int() function.
The simplest and easiest way to do this in Python is to convert a hexadecimal string to a binary string. The hexadecimal text serves as the initial input to the int() method, and the second statement is the number system’s base, which in this case is 16. The bin() function takes an integer as an argument and outputs a string containing the integer’s binary representation. This technique is quick and just requires one line of code.
Let’s start with discussing the time complexity of this method:
- The input hexadecimal string’s digit count determines the int() function’s runtime complexity, which is O(n).
- The time complexity of the bin() function, where n is the integer given value, is
O(log n).
- The effective strategy formulation has an O(n + log n) time complexity.
- The best time complexity for this is O(1).
Advantages :
- Just two built-in functions are needed, making it uncomplicated and simple to use.
- Simple implementation without the requirement of additional libraries or functions.
- Few to medium-sized inputs are suitable.
Disadvantages:
- A “0b” prefix is included in the resulting binary string, which may not be acceptable.
- Ineffective for large inputs since the time intensity increases with the hexadecimal input string’s digit count.
Let’s understand clearly through code:
Sample Code :
hex_num = "A77"
int_num = int(hex_num, 16)
bin_num = bin(int_num)[2:]
print(bin_num)
Output:
101001110111
Code Explanation :
- Initially, the value “A77” is assigned to the ‘hex_num’ variable.
- The hexadecimal string is then translated into an integer representation using the ‘int()’ method.
- The hexadecimal text to be converted is the first argument to the ‘int()’ function, and the second statement is the base of the number system, in this case 16, which is the third argument.
- The ‘int_num’ variable is provided with the outcome’s integer value.
- The hexadecimal string’s integer representation is then converted into a binary string using the ‘bin()’ method.
- The ‘bin()’ function takes an integer as an argument and outputs a string containing the integer’s representation.
- The ‘0b’ prefix is removed from the binary string using the [2:] slice notation. The ‘bin_num’ variable is assigned the resulting binary string.
- Finally, the binary string “101001110111” is produced using print() method.
Approach 2 : Using format() function.
This technique transforms the hexadecimal string’s integer representation into a binary string using the format() function. The format() function accepts two arguments: a number denoting the hexadecimal string as the first argument, and a string specifying the output format of the binary string as the second input. The binary string will have eight digits, with any needed leading zeros, according to the ’08b’ format string.
Let’s start with discussing the time complexity for this method:
- The input hexadecimal string has n digits, hence the time complexity of Approach 2 is O( logn ).
Advantages :
- With only one necessary built-in function, it is simple and easy to use.
- No additional libraries or functions are required.
- There is no 0b prefix in the resulting binary string.
- Almost nothing to medium-sized inputs were suitable.
Disadvantages :
- Inefficient for big inputs since the time challenge with the hexadecimal string’s digit number.
Let’s understand clearly through code :
Sample Code :
hex_num = "14B"
bin_num = format(int(hex_num, 16), 'b')
print(bin_num)
Output:
101001011
Code Explanation :
- Using Approach 2, this code converts the hexadecimal string “14B” into a binary string.
- Initially, the value “14B” is given to the ‘hex num’ variable. The hexadecimal string is then converted into an integer representation using the ‘int()’ method.
- The hexadecimal text to be converted is the first argument to the ‘int()’ function, and the second statement is the base of the number system, in this case 16, which is the third argument.
- The ‘format()’ function receives as its first argument the resulting integer value.
- A string that designates the output format for the binary string is provided as the second argument to the ‘format()’ function.
- The binary string will have eight digits, with any necessary leading zeros, according to the 08b format string. The ‘bin_num’ variable is given the resulting binary string.
- The binary string “101001011” is finally shown using print() function.
Approach 3 : Using loop and bitwise operators.
The ‘bin()’ function is used in this method’s loop to cycle across each character in the hexadecimal string and convert each of them to its binary number. The ‘+=’ operator is used to concatenate the result binary string to the output binary string. Each letter in the binary string will still have four binary digits thanks to the ‘zfill()’ method, which adds leading zeros as needed.
Let’s start with discussing the time complexity for this method:
- The input hexadecimal string has n digits, hence the time complexity of Approach 3 is O(n).
Advantages :
- Since it doesn’t need to keep the entire binary string in memory, it is suitable for large inputs.
- No additional libraries or functions are required.
- There is no ‘0b’ prefix in the resultant binary string.
Disadvantages :
- More intricate than the earlier techniques.
- Possibly slower than the earlier techniques for smaller inputs.
- Demands knowledge with bitwise operators.
Let’s understand clearly with the code :
Sample Code :
hex_num = "14B"
bin_num = ""
for char in hex_num:
bin_num += bin(int(char, 16))[2:].zfill(4)
print(bin_num)
Output:
000101001011
Code Explanation :
- Using Approach 3, this code converts the hexadecimal string “14B” into a binary string.
- Initially, the value “14B” is given to the ‘hex_num’ variable.
- The ‘bin_num’ variable is then provided with an empty string to store a binary string.
- The next procedure involves looping through each character in the hexadecimal string using a for loop.
- The ‘int()’ method is being used inside the loop to convert each hexadecimal character into an integer representation.
- The hexadecimal character to be converted is the first argument to the ‘int()’ method, and the second statement is the base of the number system, in this case 16, which is the third argument.
- The output to the ‘bin()’ function is the resultant integer value.
- The binary string that emerges is then put to the ‘bin_num’ variable.
- Each binary value is converted to have four digits using the ‘zfill()’ function.
- The binary string “101001011” is finally shown using print() function.
Approach 4 : Using a dictionary lookup with bitwise operators.
This technique converts each hexadecimal character to its binary number using a dictionary lookup. Each character in the hexadecimal string is iterated through while the loop searches the dictionary for its binary equivalent. The ‘+=’ operator is used to concatenate the result binary string to the output binary string.
Let’s start with discussing the time complexity for this method :
- The input hexadecimal string has n digits, hence the time complexity of Approach 4 is O(n).
Advantages :
- Due to the usage of dictionary lookup, Approach 4 is more effective than Approach 3 for bigger inputs.
- No additional libraries or functions are needed.
- There is no ‘0b’ prefix in the resulting binary string.
Disadvantages :
- More intricate than the earlier techniques.
- Need familiarity with dictionary lookup and bitwise operators.
Let’s understand clearly with code :
Sample Code :
hex_num = "14B"
bin_dict = {'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'}
bin_num = ""
for char in hex_num:
bin_num += bin_dict[char]
print(bin_num)
Output:
000101001011
Code Explanation :
- Using Approach 3, this code converts the hexadecimal string “14B” into a binary string.
- Initially, the value “14B” is given to the ‘hex num’ variable.
- In the first line, the input hexadecimal text to be converted to binary is initialised in the variable ‘hex_num’.
- By mapping every hexadecimal digit to its matching binary form, it now generates a dictionary called ‘bin_dict’.
- The third line sets the binary representation of the input hexadecimal string in the variable ‘bin_num’ to an empty string.
- Each character in the input hexadecimal string ‘hex_num’ is iterated over in this loop. It finds the corresponding binary value for each character in the ‘bin_dict’ dictionary and adds it to the ‘bin_num’ string.
- The binary string “101001011” is finally shown using print() function.
Best approach
Approach : To convert using ‘bin()’ function and ‘int()’ function.
The approach that jumps out among other approaches is using the ‘bin()’ function and ‘int()’ function—is the best way to convert hexadecimal to binary in Python.
- Because the bin() and int() technique is a built-in one in Python, it has the benefit of not requiring any other libraries or methods.
- The bin() function gives back a string that represents the binary number, making it simple to use elsewhere in the programme.
- Binary strings can also be transformed into integers using the int() function, making it simple to switch between multiple number systems.
- When dealing with lengthy hexadecimal texts, the bin() and int() methods are quicker than manually converting each hexadecimal digit to binary.
- Its time complexity is O(1). It is additionally lightweight and simple to develop as it doesn’t require any other libraries or functions.
- The bin() and int() technique can be used for a variety of applications and is simple to incorporate into other Python scripts.
- Working with data that is represented in hexadecimal format, such as network packets or file formats, makes use of this strategy extremely advantageous.
- It is simple for developers to understand and use the bin() and int() techniques to convert hexadecimal to binary in Python because it is well documented.
- Finally, since Python has a standard way of converting between multiple number systems, employing the bin() and int() approach can make code more readable and maintainable.
Sample Problem
Sample Problem 1
Rulefield is a networking company and it has been working for managing network traffic flow, the following txt file was received in the mail id of John, Manager has asked him to get the binary value so that they can authenticate that txt file is safe or not.
Solution:
- In this function, the hexadecimal string is first translated into its equivalent decimal integer representation using the ‘int()’ method. To indicate that the input string is in base-16 format, we pass the 16 parameter.
- Then, we turn the decimal number into a binary string using the ‘bin()’ function. The prefix ‘0b’ that is usually appended to the binary string is removed using the [2:] slice.
- Lastly, if necessary, we add zeros to the binary string using the ‘zfill()’ technique to make sure the string is 8 characters long. This is necessary because each hexadecimal number maps to 4 binary digits, and we need to make absolutely sure the binary string is 8 bits long.
- In this code, we first use the ‘open()’ method and the ‘r’ mode to open the file ‘data.txt’ for reading. After that, we loop through each line in the file using a for loop. To get away from any newline characters, we employ the ‘strip()’ technique.
- To convert the hexadecimal number to binary, we then execute the earlier described hex_to_bin() function. The function receives the line variable as input.
- Then, using the f-string notation, we print both the original hexadecimal integer and its binary representation.
Given:
Data.txt
1A
14B
Approach : Using bin() and int() function.
Code :
def hex_to_bin(hex_str):
dec_num = int(hex_str, 16)
bin_str = bin(dec_num)[2:]
bin_str = bin_str.zfill(8)
return bin_str
with open('data.txt', 'r') as f:
for line in f:
line = line.strip()
binary = hex_to_bin(line)
print(f'{line}: {binary}')
Output:
1A: 00011010
14B: 101001011
Sample Problem 2:
John is involved in a job that calls for us to convert a collection of hexadecimal strings into the appropriate binary forms. According to reports, he presents the findings in a neatly laid out chart. To complete the job, John is only allowed to use the format() method.
Solution:
- The first line of this code defines the hex_list, a collection of hexadecimal strings. Then, using the ‘format()’ method to format the column headings with a set width of 10 characters, we print the table’s header row.
- Then, a for loop is used to repeatedly iterate through the hexadecimal strings in the hex_list. Using the ‘int()’ method with a base of 16, we translate each string into its corresponding decimal integer.
- The decimal integer is then transformed into an 8-digit binary string using the ‘format()’ method. We want to format the integer as an 8-digit binary string with leading zeros, if necessary, according to the {:08b} format specifier.
- Lastly, we print the table’s result row by formatting the hexadecimal and binary strings with a predetermined width of 10 characters using the format() method.
Code:
hex_list = ['14A', '2B', 'C0']
print('{:<10} {:<10}'.format('Hex', 'Binary'))
for hex_str in hex_list:
dec_num = int(hex_str, 16)
bin_str = '{:08b}'.format(dec_num)
print('{:<10} {:<10}'.format(hex_str, bin_str))
Output:
14A 101001010
2B 00101011
C0 11000000
Sample Problem 3:
Consider John as a data analyst who is tasked with examining a sizable dataset that comprises the hexadecimal values of the colours used in e-commerce websites. In order to conduct specific analyses and calculations, you must convert these hexadecimal values into binary values.
Solution:
- In this code, we first build a dictionary called ‘hex_dict’, which uses bitwise operations to map each hexadecimal digit to its corresponding 4-bit binary value.
- The ‘hex_to_bin’ function, which accepts the hexadecimal value ‘hex_val’ as input and outputs the matching binary value, is then defined.
- To save the binary value, we initialise an empty string binary inside the function. Next, after iterating over each character in the hexadecimal value, we look for its matching binary value in the ‘hex_dict’ dictionary. This binary value is added to the binary string.
- The binary string containing the supplied hexadecimal value’s binary value is then returned.
Code :
def hex_to_bin(hex_val):
hex_dict = {
'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'
}
bin = ""
for char in hex_val:
bin += hex_dict[char]
return bin
hex_val = "14B"
binary_val = hex_to_bin(hex_val)
print(binary_val)
Output:
000101001011
Sample Problem 4:
A computer network expert John is looking into a network problem and needs to convert a MAC address from hexadecimal to binary code in order to better understand the network traffic flow. The MAC address is given as AF:BF:DF:FF:CF:FF.
Solution:
- In this example, a function called hex to bin is defined. It accepts a hexadecimal string as input and outputs a binary string.
- The function is to convert each hexadecimal digit to its matching binary value using the dictionary hex to bin dict.
- The binary form of the hexadecimal text will subsequently be saved in an empty string called binary str, which the function initialises. The function uses a for loop to loop through each hexadecimal digit in the supplied text.
- Throughout the loop, the method uses the dictionary lookup ‘hex_to_bin_dict[hex digit.lower()]’ to translate each hexadecimal digit into its binary equivalent before appending it to the ‘binary_str’.
- Hexadecimal digits in uppercase are changed to lowercase using the lower() method so that they can be searched up in the dictionary.
- The method finally returns the entire binary string.
Code :
def hex_to_bin(hex_str):
hex_to_bin_dict = {
'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'
}
binary_str = ""
for hex_digit in hex_str:
binary_str += hex_to_bin_dict[hex_digit.lower()]
return binary_str
hex_str = "AF:BF:DF:FF:CF:FF"
mac_address = hex_str.replace(':', '')
binary_str = hex_to_bin(mac_address)
print(binary_str)
Output:
101011111011111111011111111111111100111111111111
Conclusion
In this topic, we looked at four distinct ways to do hexadecimal to binary conversions in Python. The ideal way to use it will vary depending on the particular use case and each method’s benefits and drawbacks.
Approach 1, which employs the ‘bin()’ and ‘int()’ functions, is the most straightforward and understandable, making it a suitable choice for beginners. It is the quickest approach in regards to time complexity because its time complexity is O(1). It is additionally lightweight and simple to develop because it doesn’t involve any other libraries or functions.
Approach 2 is a versatile approach that can handle many input formats and binary output formats since it employs the format() function. However, because it involves string formatting operations, it has a higher time complexity of O(log n).
Approach 3 is a more labour-intensive method for converting hexadecimal to binary and makes use of a loop and bitwise operators. Although it has an O(n) time complexity, it offers more fine-grained control over the conversion process and might be beneficial in some situations.
Method 4 is a quick approach that can handle big input quantities since it utilises a dictionary lookup and bitwise operators.It can be optimised for some use cases despite having an O(n) time complexity. For beginners, it could be more difficult to comprehend and use.
In general, the optimal approach to take depends on the specific use situation. Method 1 is the best choice if simplicity and speed are your top requirements. Method 2 might be a better option if adaptability and customization are priorities. Method 3 might be helpful if more accurate determination over the conversion process is required. The best option may be Method 4 for high input sizes.
In conclusion, effective and precise programming requires an awareness of the various Python conversion techniques for hexadecimal to binary. Each method has benefits as well as drawbacks, so choosing the optimal one for a particular use case involves careful consideration of factors like input size, speed, and flexibility.