Cover Image for How to convert hexadecimal to binary in python
419 views

How to convert hexadecimal to binary in python

To convert a hexadecimal (hex) number to binary in Python, you can use the built-in bin() function. This function takes a hexadecimal number as a string and returns its binary representation as a string. Here’s how you can do it:

Python
# Hexadecimal number as a string
hex_number = "1A3"

# Convert to binary
binary_number = bin(int(hex_number, 16))[2:]

# Print the binary representation
print(binary_number)

In this code:

  • int(hex_number, 16) converts the hexadecimal string hex_number to an integer using base 16 (hexadecimal).
  • bin(...) converts the integer to a binary string with the prefix “0b” (e.g., “0b11010” for the decimal number 26).
  • [2:] slices the string to remove the “0b” prefix, leaving you with the pure binary representation.

When you run this code with the hex_number provided, it will print the binary representation:

Plaintext
11010011

This demonstrates how to convert a hexadecimal number to its binary equivalent using Python.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS