Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Convert a Number to Its Binary Representation

Python Convert a Number to Its Binary Representation

Document Object Reference Manual Python3 Examples

In Python, we can use the built-in bin() function to convert an integer into a binary string. The function returns a string starting with "0b", indicating a binary number.

Example

Define an integer

number

=

42

Convert it to a binary string with the bin() function

binary_representation

=

bin

(

number

)

Print the result

print

(

binary_representation

)

Code analysis:

  1. number = 42: define an integer variable numberwith the value 42.
  2. binary_representation = bin(number): When using bin() function converts the integer number to a binary string; the result is stored in the binary_representation variable.
  3. print(binary_representation): print the binary string.

Output result:

0b101010

Document Object Reference Manual Python3 Examples