How to Print the Binary Representation of a Number in Python?

Estimated read time 1 min read

To print the binary representation of a number in Python, you can use the built-in bin() function. The bin() function takes an integer as an argument and returns its binary representation as a string. Here’s an example:

# Convert decimal number to binary
decimal_number = 42
binary_string = bin(decimal_number)

# Print the binary string
print(binary_string)

Output:

0b101010

In this example, we convert the decimal number 42 to its binary representation using the bin() function. The resulting binary string is “0b101010”, which consists of the prefix “0b” followed by the binary digits representing the number.

If you want to print just the binary digits without the prefix, you can slice the binary string starting from index 2 (which skips the prefix) using the following code:

# Print just the binary digits
print(binary_string[2:])

Output:

101010

This will print just the binary digits, without the prefix “0b”.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply