SerVB
08/06/2021, 4:45 PM-128
from 128
.
First attempt:
>>> int.from_bytes((128).to_bytes(2, 'little', signed=True)[:1], 'little', signed=True)
-128
Quite long. Second attempt:
>>> (128).__add__(0x80).__and__(0xFF).__sub__(0x80) # From Hacker's Delight (Sign Extension)
-128
Or ((128 + 0x80) & 0xFF) - 0x80
, but I found the former better – it will show that these are some low level operations, not the code from user's codebase.
The second attempt is better. Looks like this is the way I will use. Any ideas on making it even shorter?
In JS, bit operations are always 32-bit, so | 0
will truncate to 32 bits (to Int), and Byte and Short are made using shifts like 128 << 24 >> 24
, so 1 operation for Int and 2 for Byte and Short. We have 3 operations for every integer type for now.
On the other hand, for unsigned integers, it seems it will be easy to just do something like (256) & 0xFF
(for UByte) – this is cool.