Python Bin | Count total bits in a number
Last Updated :
05 May, 2023
Given a positive number n, count total bit in it.
Examples:
Input : 13
Output : 4
Binary representation of 13 is 1101
Input : 183
Output : 8
Input : 4096
Output : 13
We have existing solution for this problem please refer Count total bits in a number link.
Approach#1: We can solve this problem quickly in Python using bin() function. Convert number into it's binary using bin() function and remove starting two characters '0b' of output binary string because bin function appends '0b' as prefix in output string. Now print length of binary string that will be the count of bits in binary representation of input number.
Python3
# Function to count total bits in a number
def countTotalBits(num):
# convert number into it's binary and
# remove first two characters .
binary = bin(num)[2:]
print(len(binary))
# Driver program
if __name__ == "__main__":
num = 13
countTotalBits(num)
Approach#2: We can solve this problem by simply using bit_length function of integer. This function returns the number of bits required to represent the number in binary form.
Python3
# Function to count total bits in a number
def countTotalBits(num):
# bit_length function return
# total bits in number
B_len = num.bit_length()
print("Total bits in binary are : ", B_len)
# Driver program
if __name__ == "__main__":
num = 13
countTotalBits(num)
OutputTotal bits in binary are : 4
Approach#3: Using math
approach to count the total number of bits in a number is to use the logarithmic function log2() from the math module. Since the logarithmic function base 2 tells us the number of bits required to represent a number in binary, we can use it to calculate the total number of bits in a number.
Algorithm
1. Import the math module.
2. Define a function count_bits that takes an integer num as input.
3. Calculate the logarithm base 2 of the input number using the log2() function from the math module.
4. Add 1 to the result of the logarithm calculation to account for the sign bit (if the number is negative).
5. Return the integer value of the result.
Python3
import math
def count_bits(num):
return int(math.log2(num)) + 1
num=13
print(count_bits(num))
Time complexity:
The time complexity of this function is O(1) because the log2() function and the addition operation both have constant time complexity.
Auxiliary Space:
The space complexity of this function is O(1) because the only extra space used is for storing the integer value of the result, which has a constant size regardless of the input size.
METHOD 4:Using defaultdict
APPRAOCH:
This program counts the total number of bits in a given number using a defaultdict data structure.
ALGORITHM:
1.Convert the given number to its binary representation using the built-in bin() function.
2.Create a defaultdict to count the number of '0's and '1's in the binary representation.
3.Iterate over the binary representation and increment the corresponding count in the defaultdict.
4.Add the counts of '0's and '1's to get the total number of bits in the binary representation.
Python3
from collections import defaultdict
# Function to count the number of bits
def count_bits(num):
binary = bin(num)[2:]
bit_count = defaultdict(int)
for bit in binary:
bit_count[bit] += 1
return bit_count['1'] + bit_count['0']
# Driver Code
num = 13
bits = count_bits(num)
print("Total bits in", num, ":", bits)
OutputTotal bits in 13 : 4
Time Complexity: O(log n), where n is the given number.
Space Complexity: O(log n), where n is the given number, due to the storage of the binary representation in memory and the creation of the defaultdict.
Similar Reads
numpy.bincount() in Python In an array of +ve integers, the numpy.bincount() method counts the occurrence of each element. Each bin value is the occurrence of its index. One can also set the bin size accordingly. Syntax : numpy.bincount(arr, weights = None, min_len = 0) Parameters : arr : [array_like, 1D]Input array, having p
2 min read
Convert Bytes To Bits in Python Converting bytes to bits in Python involves representing each byte in its binary form, where each byte is composed of 8 bits. For example , a byte like 0xAB (which is 171 in decimal) would be represented as '10101011' in binary. Letâs explore a few techniques to convert bytes to bits in Python.Using
2 min read
Different ways to Invert the Binary bits in Python We know how binary value for numbers look like. For example, the binary value for 10 (Number Ten) is 1010 (binary value).Sometimes it is required to inverse the bits i.e., 0's to 1's ( zeros to ones) and 1's to 0's (ones to zeros). Here are there few ways by which we can inverse the bits in Python.U
3 min read
How to Convert Bytes to Int in Python? Converting bytes to integers in Python involves interpreting a sequence of byte data as a numerical value. For example, if you have the byte sequence b'\x00\x01', it can be converted to the integer 1.Using int.from_bytes()int.from_bytes() method is used to convert a byte object into an integer. It a
3 min read
How to Convert Int to Bytes in Python? The task of converting an integer to bytes in Python involves representing a numerical value in its binary form for storage, transmission, or processing. For example, the integer 5 can be converted into bytes, resulting in a binary representation like b'\x00\x05' or b'\x05', depending on the chosen
2 min read
Reverse bits of a positive integer number in Python Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this pr
4 min read