Created
July 10, 2022 08:59
-
-
Save plvhx/f0d9d66078c5e0d1fa6f73d7657a91c2 to your computer and use it in GitHub Desktop.
lsb to msb (two's complement)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# https://en.wikipedia.org/wiki/Two%27s_complement#Working_from_LSB_towards_MSB | |
# | |
# (c) 2022 Paulus Gandung Prakosa <[email protected]> | |
# | |
import sys | |
import math | |
num = int(sys.argv[1]) | |
res = 0 | |
exp = 32 | |
if num == 0 or num == 1: | |
print(~(num & (pow(2, num) - 1)) + 1) | |
sys.exit(0) | |
for i in range(0, math.floor(math.log2(num)) + 1): | |
if num & (pow(2, i)) > 0: | |
res += ~((1 << i) & (pow(2, exp) - 1)) + 1 | |
print(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment