Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Created January 30, 2024 08:10
Show Gist options
  • Save shiracamus/5bf784bcb655730319f137e256f42c2f to your computer and use it in GitHub Desktop.
Save shiracamus/5bf784bcb655730319f137e256f42c2f to your computer and use it in GitHub Desktop.
def signed(value, bits=8):
return (value & ((sign := (1 << (bits - 1))) - 1)) - (value & sign)
print(signed(0x7f)) # 127
print(signed(0x80)) # -128
print(signed(0x81)) # -127
print(signed(0x7fff)) # -1
print(signed(0x7fff, 16)) # 32767
print(signed(0x8000, 16)) # -32768
print(signed(0x8001, 16)) # -32767
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment