Python convert bin to hex

Convert binary, octal, decimal, and hexadecimal in Python

In Python, you can handle numbers and strings in binary (bin), octal (oct), and hexadecimal (hex) formats, as well as in decimal. These formats can be converted among each other.

See the following article for the basics of conversion between the string ( str ) and the number ( int , float ).

Represent integers in binary, octal, and hexadecimal formats

Integers ( int ) can be expressed in binary, octal, and hexadecimal formats by appending the prefixes 0b , 0o , and 0x . However, the print() function will present the output in decimal notation.

bin_num = 0b10 oct_num = 0o10 hex_num = 0x10 print(bin_num) print(oct_num) print(hex_num) # 2 # 8 # 16 

The prefixes can also be denoted in uppercase forms as 0B , 0O , and 0X .

Bin_num = 0B10 Oct_num = 0O10 Hex_num = 0X10 print(Bin_num) print(Oct_num) print(Hex_num) # 2 # 8 # 16 

Despite the prefix, the data type remains int .

print(type(bin_num)) print(type(oct_num)) print(type(hex_num)) # # # print(type(Bin_num)) print(type(Oct_num)) print(type(Hex_num)) # # # 

These numbers can be subjected to standard arithmetic operations.

result = 0b10 * 0o10 + 0x10 print(result) # 32 

In Python3.6 and later, you can insert underscores _ within numbers for better readability. Inserting consecutive underscores raises an error, but you can include as many non-consecutive underscores as you like.

The underscore can be used as a delimiter for better readability in large numbers. For example, inserting an underscore every four digits can make the number more readable.

print(0b111111111111 == 0b1_1_1_1_1_1_1_1_1_1_1_1) # True bin_num = 0b1111_1111_1111 print(bin_num) # 4095 

Convert a number to a binary, octal, and hexadecimal string

You can convert a number to a binary, octal, or hexadecimal string using the following functions:

  • Built-in function bin() , oct() , hex()
  • Built-in function format() , string method str.format() , f-strings

The article also explains how to obtain a string in two’s complement representation for a negative value.

bin() , oct() , and hex()

The built-in functions bin() , oct() , and hex() convert numbers into binary, octal, and hexadecimal strings. Each function returns a string prefixed with 0b , 0o , and 0x .

i = 255 print(bin(i)) print(oct(i)) print(hex(i)) # 0b11111111 # 0o377 # 0xff print(type(bin(i))) print(type(oct(i))) print(type(hex(i))) # # # 

If the prefix is not required, you can use slice notation [2:] to extract the remainder of the string, or you can employ the format() function as described next.

print(bin(i)[2:]) print(oct(i)[2:]) print(hex(i)[2:]) # 11111111 # 377 # ff 

To convert into a decimal string, simply use str() .

print(str(i)) # 255 print(type(str(i))) # 

format() , str.format() , and f-strings

The built-in function format() , the string method str.format() , and f-strings can also be used to convert a number to a binary, octal, and hexadecimal string.

You can convert a number to a binary, octal, or hexadecimal string by specifying b , o , or x in the format specification string, which is used as the second argument of format() .

i = 255 print(format(i, 'b')) print(format(i, 'o')) print(format(i, 'x')) # 11111111 # 377 # ff print(type(format(i, 'b'))) print(type(format(i, 'o'))) print(type(format(i, 'x'))) # # # 

To append the prefix 0b , 0o , and 0x to the output string, include # in the format specification string.

print(format(i, '#b')) print(format(i, '#o')) print(format(i, '#x')) # 0b11111111 # 0o377 # 0xff 

It is also possible to pad the number with zeros to a certain length. However, when padding a number with a prefix, remember to include the two characters of the prefix in your count.

print(format(i, '08b')) print(format(i, '08o')) print(format(i, '08x')) # 11111111 # 00000377 # 000000ff print(format(i, '#010b')) print(format(i, '#010o')) print(format(i, '#010x')) # 0b11111111 # 0o00000377 # 0x000000ff 

The string method str.format() can also perform the same conversion.

print(' '.format(i)) print(' '.format(i)) print(' '.format(i)) # 11111111 # 00000377 # 000000ff 

For details about format() and str.format() , including format specification strings, see the following article.

In Python 3.6 or later, you can also use f-strings to write more concisely.

print(f'i:08b>') print(f'i:08o>') print(f'i:08x>') # 11111111 # 00000377 # 000000ff 

Convert a negative integer to a string in two’s complement representation

The bin() or format() functions convert negative integers into their absolute values, prefixed with a minus sign.

x = -9 print(x) print(bin(x)) # -9 # -0b1001 

Python performs bitwise operations on negative integers in two’s complement representation. So, if you want the binary string in two’s complement form, use the bitwise-and operator ( & ) with the maximum number required for your digit size. For example, use 0b1111 (= 0xf ) for 4-bit, 0xff for 8-bit, and 0xffff for 16-bit representations.

print(bin(x & 0xff)) print(format(x & 0xffff, 'x')) # 0b11110111 # fff7 

Convert a binary, octal, and hexadecimal string to a number

int()

You can use the built-in function int() to convert a binary, octal, or hexadecimal string into a number.

The int() function accepts a string and a base as arguments to convert the string into an integer. The base signifies the number system to be used. If the base is omitted, the function assumes the string is in decimal.

print(int('10')) print(int('10', 2)) print(int('10', 8)) print(int('10', 16)) # 10 # 2 # 8 # 16 print(type(int('10'))) print(type(int('10', 2))) print(type(int('10', 8))) print(type(int('10', 16))) # # # # 

If the radix is set to 0 , the function determines the base according to the prefix ( 0b , 0o , 0x or 0B , 0O , 0X ).

print(int('0b10', 0)) print(int('0o10', 0)) print(int('0x10', 0)) # 2 # 8 # 16 print(int('0B10', 0)) print(int('0O10', 0)) print(int('0X10', 0)) # 2 # 8 # 16 

With the radix set to 0 , a string without a prefix is interpreted as a decimal number. Note that leading zeros in the string will cause an error.

print(int('10', 0)) # 10 # print(int('010', 0)) # ValueError: invalid literal for int() with base 0: '010' 

In other cases, a string padded with 0 can be successfully converted.

print(int('010')) # 10 print(int('00ff', 16)) print(int('0x00ff', 0)) # 255 # 255 

The function raises an error if the string cannot be converted according to the specified radix or prefix.

# print(int('ff', 2)) # ValueError: invalid literal for int() with base 2: 'ff' # print(int('0a10', 0)) # ValueError: invalid literal for int() with base 0: '0a10' # print(int('0bff', 0)) # ValueError: invalid literal for int() with base 0: '0bff' 

Practical examples

Arithmetic with binary strings

For example, to perform operations on binary strings prefixed with 0b , convert them into an integer int , conduct the desired operation, and then transform them back into a string str .

a = '0b1001' b = '0b0011' c = int(a, 0) + int(b, 0) print(c) print(bin(c)) # 12 # 0b1100 

Convert between binary, octal, and hexadecimal numbers

It is straightforward to convert binary, octal, and hexadecimal strings to one another by converting them first to the int format and then into any desired format.

You can control the addition of zero-padding and prefixes using the formatting specification string.

a_0b = '0b1110001010011' print(format(int(a, 0), '#010x')) # 0x00000009 print(format(int(a, 0), '#010o')) # 0o00000011 

Источник

Convert Binary to Hex in Python

Convert Binary to Hex in Python

  1. Create and Make Use of a User-Defined Function to Convert Binary to Hex in Python
  2. Use the int() and the hex() Functions to Convert Binary to Hex in Python
  3. Use the binascii Module to Convert Binary to Hex in Python
  4. Use the format() Function to Convert Binary to Hex in Python
  5. Use f-strings to Convert Binary to Hex in Python

Binary and Hexadecimal are two of the many number systems in which a numeric value can be represented in Python. This tutorial focuses on the different ways available to convert Binary to Hex in Python.

Create and Make Use of a User-Defined Function to Convert Binary to Hex in Python

We can create our user-defined function with the help of the while loop and put it in place to convert a value in Binary to Hex in Python.

The following code uses a user-defined function to convert Binary to Hex in Python.

print("Enter the Binary Number: ", end="") bnum = int(input())  h = 0 m = 1 chk = 1 i = 0 hnum = [] while bnum!=0:  rem = bnum%10  h = h + (rem*m)  if chk%4==0:  if h10:  hnum.insert(i, chr(h+48))  else:  hnum.insert(i, chr(h+55))  m = 1  h = 0  chk = 1  i = i+1  else:  m = m*2  chk = chk+1  bnum = int(bnum/10)  if chk!=1:  hnum.insert(i, chr(h+48)) if chk==1:  i = i-1  print("\nEquivalent Hexadecimal Value = ", end="") while i>=0:  print(end=hnum[i])  i = i-1 print() 

The above code provides the following output.

Enter the Binary Number: 0101101 Equivalent Hexadecimal Value = 2D 

Use the int() and the hex() Functions to Convert Binary to Hex in Python

We make use of both the int() and the hex() functions to implement this method.

Firstly, the int() method is utilized to convert the given binary number into an integer value. After this process, the hex() function converts the newly found integer value into a hexadecimal value.

The following code uses the int() and the hex() functions to convert Binary to Hex in Python.

The above code provides the following output.

Use the binascii Module to Convert Binary to Hex in Python

Python provides a binascii module from Python 3 onwards that can be utilized to convert Binary to Hex in Python. The binascii module needs to be manually imported to the Python code in order for this method to work.

This method opens a text file, takes in the content of the file, and can return the hex value of the given data in the file using the hexlify() function.

The following code uses the binascii module to convert Binary to Hex in Python.

import binascii bFile = open('ANYBINFILE.exe','rb') bData = bFile.read(8) print(binascii.hexlify(bData)) 

Use the format() Function to Convert Binary to Hex in Python

The format() function is one of the ways in which string formatting can be implemented in Python. The format() function is utilized to provide the formatted string inside the <> curly brackets.

The following code uses the format() function to convert Binary to Hex in Python.

print("4X>".format(int("0101101", 2))) 

The above code provides the following output.

Use f-strings to Convert Binary to Hex in Python

Being introduced with Python 3.6, it is relatively the newest method in Python to implement string formatting. It can be used in the newer and latest versions of Python.

It is more efficient than its other two peers, % sign and str.format() , as it is faster and easier to understand. It also helps in implementing string formatting in Python at a faster rate than the other two methods.

The following code uses f-strings to convert Binary to Hex in Python.

bstr = '0101101' hexstr = f'int(bstr, 2):X>' print(hexstr) 

The above code provides the following output.

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Related Article — Python Binary

Related Article — Python Hex

Copyright © 2023. All right reserved

Источник

Читайте также:  Apache poi excel to html
Оцените статью