2018年1月11日 星期四

Python: Convert an integer to binary keep leading zeros

Python: Convert an integer to binary keep leading zeros

Python Basic: Exercise-140 with Solution

Write a Python program to convert an integer to binary keep leading zeros.
Sample Solution:-
x = 12
print(format(x, '08b'))
print(format(x, '010b'))

a=bin(254)[2:].zfill(8)
print("254=",a)

bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
b=bin8(6)
print("6=",b)

========= RESTART: F:/Python_APSC/py-ex-basic-140.py =============
00001100
0000001100
254= 11111110
6= 00000110
>>> 

沒有留言:

張貼留言