Aug-07-2018, 05:54 AM
Aug-07-2018, 10:05 AM
In python, integers conceptually have a semi-infinite number of bits, so for example if
For example the sequence of bits of -23762 is the two's complement of the bits of 23761. You can confirm this by using a 32 bits mask for example
>>> bin(37) '0b100101'the integer 37 is represented by the infinite sequence
...000000100101
. It means that the two's complement ~37
is a sequence starting with an infinite number of 1's, but of course it is not stored this way. Instead, it is stored as the negative number -38
. For every integer, one hasassert ~x == -(x+1)So you don't see the infinite sequence, but with regards to bitwise operations, you need to consider negative integers as a sequence of bits starting with an infinite number of 1s.
For example the sequence of bits of -23762 is the two's complement of the bits of 23761. You can confirm this by using a 32 bits mask for example
>>> mask = (1 << 32) - 1 >>> bin(mask) '0b11111111111111111111111111111111' >>> bin(23761) '0b101110011010001' >>> bin(-23762 & mask) '0b11111111111111111010001100101110'
Aug-08-2018, 12:46 AM
now i see the complication. the leading sequence is infinite making my attempts to do things in just 8 bits not workable with 16 bit values. i was trying to get the low order 8 bits from the way a two's complement based machine would store a number that might need 16 bits and/or might be negative. once i realized i was not getting two's complement form from bin(), i tried to do it myself in just 8 bits. i was thinking that we should have a bin2() that would give a two's complement form for negative numbers. but how many 1's would they need in front? 32? 64? 65536?
so now i made this:
bin2.py
now, how to convert in reverse? is '0b10000000' -128 or 128?
so now i made this:
bin2.py
def bin2(n,bits=64): return bin(n&((1<<bits)-1)) for i in range(-16,16): print(i,bin2(i,5))i plan to keep the first 0b10 lines.
now, how to convert in reverse? is '0b10000000' -128 or 128?