首先使用bin()
函数将数字转换为二进制。然后跳过二进制表示形式的前两个字符,因为bin()
在数字的二进制表示形式中将0b附加为前缀,并反转其余部分。从另一个字符开始,并将其反转,直到从左数倒数第二个字符。将反向的二进制字符串转换为整数。
integernumber(n,bit_size) /* n is the number and bit_size is the bitsize */ Step 1: first convert number into binary . Step 2: skip the first two characters of binary representation string and reverse. Step 3: remaining string and then append 0’s after it. Step 4: from the last character and reverse it until second last character from the left. Step 5: converts reversed binary string into an integer.
# Python Program reverse bits of positive integer number defintegernumber(n,bit_size): bin_number = bin(n) reverse_number = bin_number[-1:1:-1] reverse_number = reverse_number + (bit_size - len(reverse_number))*'0' print ("Reverse Bits ::>",int(reverse_number,2)) # Driver program if __name__ == "__main__": n = int(input("Enter Number ::>")) bit_size = int(input("Enter Bit Size ::>")) integernumber(n,bit_size)
Enter Number ::>1 Enter Bit Size ::>32 Reverse Bits ::> 2147483648 Enter Number ::>2147483648 Enter Bit Size ::>32 Reverse Bits ::> 1