Paul Rubin wrote:
jrlen balane <[EMAIL PROTECTED]> writes:

would i be able to perform bitwise operation with the result?
say, i want to get the two's complement of the result, is this correct:

twos_complement = (~ hex(hi + lo)) + 1


You can do bit operations, but hex(n) is the hex string for n, which
is not what you want.

If you want the hex form of the two's complement, just say

   hex(-(hi+lo) & 0xff)

assuming you want one byte, or

   hex(-(hi+lo) & 0xffff)

for two bytes.

More generally though, the "flip the bits and add one" of two's complement is just a hardware implementation trick for "2*n - x".


When not working at the hardware level, just go with the definition:

Py> def complement(val, limit=256):
...   if val >= limit or val < 0:
...     raise ValueError("Value out of range for complemented format")
...   if val == 0:
...     return 0
...   return limit - val
...
Py> hex(complement(0x55))
'0xab'
Py> hex(complement(0x55, 256*256))
'0xffab'

Cheers,
Nick.

--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---------------------------------------------------------------
            http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to