Python Slicing | Extract ‘k’ bits from a given position
Last Updated : 17 May, 2023
How to extract ‘k’ bits from a given position ‘p’ in a number? Examples:
Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get only 01000 i.e 8.
We have existing solution for this problem please refer Extract ‘k’ bits from a given position in a number link. We can solve this problem quickly in python using slicing. Approach is simple,
- Convert given number into it's binary using bin() function and remove first two characters '0b' from it, because bin function appends '0b' as prefix in output binary string.
- We need to start extracting k bits from starting position p from right, that means end index of extracted sub-string will be end = (len(binary) - p) and start index will be start = end - k + 1 of original binary string.
- Convert extracted sub-string into decimal again.
Python3 # Function to extract ‘k’ bits from a given # position in a number def extractKBits(num,k,p): # convert number into binary first binary = bin(num) # remove first two characters binary = binary[2:] end = len(binary) - p start = end - k + 1 # extract k bit sub-string kBitSubStr = binary[start : end+1] # convert extracted sub-string into decimal again print (int(kBitSubStr,2)) # Driver program if __name__ == "__main__": num = 171 k = 5 p = 2 extractKBits(num,k,p)
Output:
21
Time Complexity: O(logn)
Space Complexity: O(logn)
Method#2: Using Bitwise Operators
Approach
This approach defines a function named extract_bits that takes three arguments: number, k, and p. It returns the decimal value of the k bits starting from position p (from right to left) in the binary representation of number. The function first right-shifts the number by p-1 bits to get the desired bits at the rightmost end of the number. Then, it creates a mask by left-shifting 1 by k bits and subtracting 1 to get a binary number consisting of k ones. It then bitwise-ANDs the shifted number with the mask to extract the k bits. Finally, it converts the extracted bits to a binary string and then to an integer to get the decimal value.
Algorithm
1. Right shift the given number by p-1 bits to get the desired bits at the rightmost end of the number.
2. Mask the rightmost k bits to get rid of any additional bits on the left.
3. Convert the resulting bits to decimal using the int() function.
Python3 def extract_bits(number, k, p): # Right shift the number by p-1 bits to get the desired bits at the rightmost end of the number shifted_number = number >> (p-1) # Mask the rightmost k bits to get rid of any additional bits on the left mask = (1 << k) - 1 extracted_bits = shifted_number & mask # Convert the extracted bits to decimal extracted_number = bin(extracted_bits)[2:] decimal_value = int(extracted_number, 2) return decimal_value number = 171 k = 5 p = 2 print(extract_bits(number, k, p))
Time Complexity: O(1)
Space Complexity: O(1)
Approach#3: Using lambda
This approach takes a decimal number num, the number of bits k, and the position of the bits p as input. It converts num to a binary string using the bin() function, removes the '0b' prefix from the string, and extracts a substring of length k starting from position p. Finally, the substring is converted back to an integer using the int() function with a base of 2.
Algorithm
1. Convert the decimal number to a binary string using bin().
2. Remove the '0b' prefix from the binary string.
3. Extract a substring of length k starting from position p.
4. Convert the substring back to an integer using int() with a base of 2.
5. Return the extracted integer.
Python3 extract_bits = lambda num, k, p: int(bin(num)[2:][p:p+k], 2) print(extract_bits(171, 5, 2))
Time complexity: O(1), The time complexity of bin() and int() is O(log n), where n is the input number, but the input num is limited to 32 bits (in most implementations of Python), so the time complexity can be considered constant.
Auxiliary Space: O(log n) The space complexity of bin() and int() is O(log n), where n is the input number, but the input num is limited to 32 bits (in most implementations of Python), so the space complexity can be considered constant.
Similar Reads
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
Count set bits using Python List comprehension set bits means finding how many 1s are in the binary form of a number. The set bit is any bit that is 1. List comprehension offers a quick and simple way to count these set bits. In this article, we will count set bits using Python list comprehension. Using bin()bin() function converts a number to b
2 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
Python Bin | Count total bits in a number 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 quick
3 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