Answers for "python int to hex 2's complement"

0

python int to hex 2's complement

def to_hex(val, nbits):
  return hex((val + (1 << nbits)) % (1 << nbits)).lstrip('0x')

print(to_hex(-1998995181, 16)) # c113
print(to_hex(-1998995181, 32)) # 88d9c113
print(to_hex(-1998995181, 64)) # ffffffff88d9c113
Posted by: Guest on February-20-2022
0

python hex 2's complement to int

def _to_int(val, nbits):
    i = int(val, 16)
    if i >= 2 ** (nbits - 1):
        i -= 2 ** nbits
    return i

print(to_int('c113', 16)) # -1998995181
print(to_int('88d9c113', 32)) # -1998995181
print(to_int('ffffffff88d9c113', 64)) # -1998995181
Posted by: Guest on February-20-2022
0

how to convert integer to hex signed 2's complement in python

def hex2complement(number):
    hexadecimal_result = format(number, "03X")
    return hexadecimal_result.zfill(4) # .zfill(n) adds leading 0's if the integer has less digits than n


# Examples:
# print(hex2complement(10)) outputs "000A"
# print(hex2complement(100)) outputs "0064"
# print(hex2complement(1000)) outputs "03E8"
# print(hex2complement(10000)) outputs "2710"
# print(hex2complement(100000)) outputs "186A0"
Posted by: Guest on January-03-2022

Python Answers by Framework

Browse Popular Code Answers by Language