1

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)

Stefan
  • 528
  • 4
  • 12

1 Answers1

3

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

eduffy
  • 39,140
  • 13
  • 95
  • 92
  • yes that worked thanks, you have a solution for my other (main) problem too? – Stefan Jan 21 '14 at 13:35
  • for one's comp of a specific length, you can also use xor: `0xfff ^ num`. – Corley Brigman Jan 21 '14 at 14:35
  • 2**12 is 1 followed 12 zeroes. Subtract 1 and you get 12 ones. Subtracting anything from all ones switches the bits. `1-1=0` and `1-0=1`. Basically it's doing the `xor` operation that @CorleyBrigman describes. – eduffy Jan 21 '14 at 15:25