Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
two's complment binary
#1
d'rat ... the bin() function does not give the two's complement form of negative numbers. anyone know of something that does that?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
In python, integers conceptually have a semi-infinite number of bits, so for example if
>>> 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 has
assert ~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'
Reply
#3
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
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  hex file to binary or pcap to binary baran01 1 5,689 Dec-11-2019, 10:19 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020