如何在 python 中将二进制补码转换为有符号整数

问题描述 投票:0回答:1

我有一个二进制补码的 20 位数字,我需要在 Python 中将其转换为有符号整数。 有人可以帮我解决这个问题吗?

python integer signed twos-complement
1个回答
0
投票

找到答案,应该这样做:

def twos_comp(val, bits):
    """compute the 2's complement of int value val"""
    if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
        val = val - (1 << bits) # compute negative value
    return val # return positive value as is
© www.soinside.com 2019 - 2024. All rights reserved.