Create integer variable by assigning binary value in Python

Here, we are going to learn how to create an integer variable by assigning value in binary format in Python?
Submitted by IncludeHelp, on April 26, 2019

The task is to create integer variables and assign values in binary format.

Binary value assignment

To assign value in binary format to a variable, we use 0b suffix. It tells to the compiler that the value (suffixed with 0b) is a binary value and assigns it to the variable.

Syntax to assign a binary value to the variable

    x = 0b111011

Python code to create variable by assigning binary value

In this program, we are declaring some of the variables by assigning the values in binary format, printing their types, values in decimal format and binary format.

Note: To print value in binary format, we use bin() function.

# Python code to create variable 
# by assigning binary value 

# creating number variable
# and, assigning binary value
a = 0b1010
b = 0b00000000
c = 0b11111111
d = 0b11110000
e = 0b10101010

# printing types
print("type of the variables...")
print("type of a: ", type(a))
print("type of b: ", type(b))
print("type of c: ", type(c))
print("type of d: ", type(d))
print("type of e: ", type(e))

# printing values in decimal format
print("value of the variables in decimal format...")
print("value of a: ", a)
print("value of b: ", b)
print("value of c: ", c)
print("value of d: ", d)
print("value of e: ", e)

# printing values in binary format
print("value of the variables in binary format...")
print("value of a: ", bin(a))
print("value of b: ", bin(b))
print("value of c: ", bin(c))
print("value of d: ", bin(d))
print("value of e: ", bin(e))


type of the variables...
type of a:  <class 'int'>  
type of b:  <class 'int'>  
type of c:  <class 'int'>  
type of d:  <class 'int'>  
type of e:  <class 'int'>  
value of the variables in decimal format...  
value of a:  10
value of b:  0 
value of c:  255  
value of d:  240  
value of e:  170  
value of the variables in binary format...
value of a:  0b1010  
value of b:  0b0  
value of c:  0b11111111 
value of d:  0b11110000 
value of e:  0b10101010 

Python Basic Programs »



Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.