Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
two's complment binary
#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


Messages In This Thread
two's complment binary - by Skaperen - Aug-07-2018, 05:54 AM
RE: two's complment binary - by Gribouillis - Aug-07-2018, 10:05 AM
RE: two's complment binary - by Skaperen - Aug-08-2018, 12:46 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  hex file to binary or pcap to binary baran01 1 6,975 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