Question

i'm new to python and tried to do something like that:

a=23
"{0:b}".format(a)

---> '10111'

then i want to negate it WITHOUT ones complement, the result should be '01000' but nothing seems to work

secondly i would have to fill up the left side with 0's, i found something like

"{0:12b}".format(a)
'       10111'

but it just makes the string longer filling it up with blanks

EDIT: the perfect solution for me would be

"{0:12b}".format(a)
'000000010110' 
"{0:12b}".format(~a)
'111111101001'

(which of course doesnt work this way)

Was it helpful?

Solution

Put a 0 in front of the 12 to left-pad the output with zeroes.

In [1]: "{0:012b}".format(a)
Out[1]: '000000010111'

For the ones comp, the you could do string manipulation, or the math way:

 In [2]: "{0:012b}".format(2**12-1-a)
 Out[2]: '111111101000'

Just change the 2**12 to the number of digits you want to display

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top