Python program to print number of bits to store an integer and also print number in Binary format

Here, we are implementing a python program that will print the numbers of bits to store an integer number and also print its binary value.
Submitted by IncludeHelp, on June 24, 2019

Given an integer number and we have to print numbers of bits to store the number and its binary value.

Printing number of bits to store an integer

To find the total number of bits to store an integer, we use bit_length() function, it is called with the number (an integer value) and returns the total number of bits to store the given number.

Printing binary value

To print binary value of a given integer, we use bin() function it accepts the number as an argument and returns the binary value.

Example:

    Input:
    num = 10

    Output:
    Number of bits to store the number: 4
    Binary value: 0b1010

Python code:

# Python program to print number of bits to store an integer 
# and also print number in Binary format

# input a number 
num = int(input("Enter an integer number: "))

# print the input number
print("Entered number is: ", num)

# printing number of bits to store the number
print(num, " needs ", num.bit_length(), " to store the value")

# printing binary value 
print("Binary value of ", num, " is: ", bin(num))

Output

First run:
Enter an integer number: 120
Entered number is:  120
120  needs  7  to store the value
Binary value of  120  is:  0b1111000

Second run:
Enter an integer number: 10
Entered number is:  10
10  needs  4  to store the value
Binary value of  10  is:  0b1010




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.