w3resource

Python: Convert an integer to binary keep leading zeros


Binary with Leading Zeroes

Write a Python program to convert an integer to binary that keeps leading zeros.

Converting an integer to an n-bit binary number results in its binary representation containing leading zeros up to length n. For example, to convert the integer 5 to a 6-bit binary results in 000101.
format(num, name) function with name as "0nb" to convert an integer num to a binary string with leading zeros up to length n.

Sample data : x=12
Expected output : 00001100
0000001100

Sample Solution:

Python Code:

# Define an integer variable 'x' with the value 12.
x = 12
# Print the binary representation of 'x' with leading zeros.
# The 'format' function is used with the format specifier '08b' to format 'x' as an 8-character binary string.
# It ensures that there are leading zeros to make it 8 characters long.
print(format(x, '08b'))
# Print the binary representation of 'x' with leading zeros.
# The 'format' function is used with the format specifier '010b' to format 'x' as a 10-character binary string.
# It ensures that there are leading zeros to make it 10 characters long.
print(format(x, '010b'))

Sample Output:

00001100
0000001100

For more Practice: Solve these Related Problems:

  • Write a Python function to format binary numbers with a fixed number of bits.
  • Write a Python program to display a number in binary, octal, and hexadecimal formats.
  • Write a Python function to add leading zeros dynamically based on input size.
  • Write a Python program to convert a binary string with leading zeros back to an integer.

Python Code Editor:

 

Previous: Write a Python program to valid a IP address.
Next: Write a python program to convert decimal to hexadecimal.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.