On Fri, Dec 30, 2016, at 09:47, Steve D'Aprano wrote: > Again, assume both operands are in range for an N-bit signed integer. > What's > a good way to efficiently, or at least not too inefficiently, do the > calculations in Python?
I'd do something like: bit_mask = (1 << bits) - 1 # 0xFFFF sign_bit = 1 << (bits - 1) # 0x8000 sign_ext = ~bit_mask # ...FFFFF0000 def signed(value): if value & sign_bit: return value | sign_ext else: return value & bit_mask def unsigned(value): return value & bit_mask And also avoid doing it on intermediate steps where it can be shown to not affect the result or allow the value to grow too large. -- https://mail.python.org/mailman/listinfo/python-list