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)

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

yes that worked thanks, you have a solution for my other (main) problem too?
for one's comp of a specific length, you can also use xor: 0xfff ^ num.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.