python convert integer to signed base 2 complement

Solutions on MaxInterview for python convert integer to signed base 2 complement by the best coders in the world

showing results for - "python convert integer to signed base 2 complement"
Leonie
14 Sep 2019
1def twos_comp(val, bits):
2    """compute the 2's complement of int value val"""
3    if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
4        val = val - (1 << bits)        # compute negative value
5    return val                         # return positive value as is
6  
7binary_string = '1010101010' # or whatever... no '0b' prefix
8out = twos_comp(int(binary_string,2), len(binary_string))