This Python program reads an integer from the user and checks the most significant bit (MSB) of its binary representation.
The MSB is the leftmost bit and represents the highest power of 2 in the number.
To check it, the number is first converted to binary and the first non-zero bit is examined.
def check_msb(num):
binary = bin(num)[2:] # remove '0b' prefix
msb = binary[0] if binary else '0'
print(f"Binary: {binary}")
if msb == '1':
print("The most significant bit is 1.")
else:
print("The most significant bit is 0.")
# Run the program
num = int(input("Enter a number: "))
check_msb(num)
Enter a number: 12
Binary: 1100
The most significant bit is 1.
Enter a number: 0
Binary: 0
The most significant bit is 0.
- The number is converted to a binary string using bin()
- The first character of the binary string is the MSB
- If it’s 1, the number has a high-order bit set
- If it’s 0, the number is zero or has no active leftmost bit