python - Convert from bin to int/char without loosing leading "0" -
is there anyway that
>>> int('0000001',2) 1
could save leading 0s ?
what want is, huge string of bits, in 8 , 8 bits convert int, , char, , write in file. later want read file, char, use ord(), int, , bits entered, leading 0s.
you can preserve number of initial zeroes finding first index of 1
(as binary string).
>>> s = '0000001' >>> '{}{}'.format('0'*s.index('1'),int(s,2)) '0000001' >>> s = '0000011' >>> '{}{}'.format('0'*s.index('1'),int(s,2)) '000003'
as can see, leading zeroes preserved , not number of digits.
another implementation (only zeroes included)
>>> def change(s): ... try: ... return '{}{}'.format('0'*s.index('1'),int(s,2)) ... except valueerror: ... return s ... >>> change('000000') '000000' >>> change('000001') '000001' >>> change('000011') '00003'
Comments
Post a Comment