Math operation with 16b hex in python

0

I have a start hex : "00000000FFFFFFFF000000000AF50AF5" on this one I want to perform some operations.
User enter an int value (20 for exemple).
Program do : input*100. (=2000)
Convert it in "Hex Little Endian"(=D0070000)
Replace the first 4bytes (00000000) by this new 4bytes: (=D0070000FFFFFFFF000000000AF50AF5)
Until here It's good ! Problems begin now.
Replace same hex (=D0070000) at the third position of 4bytes(00000000): (=D0070000FFFFFFFFD00700000AF50AF5)
And finally substract this same hex (=D0070000) to the second postion of 4bytes (FFFFFFFF): (=2FF8FFFF)
Final hex : "D00700002FF8FFFFD00700000AF50AF5"

I don't understand how can I mention to my program the position of 4bytes (1,2,3 or 4)to replace.

user_int_value=int(input("enter num: "))*100 #user input*100
start_hex=bytes.fromhex("00000000FFFFFFFF000000000AF50AF5") #Starting hex
num_tot=hex(int.from_bytes(user_int_value.to_bytes(16, 'little'), 'big')) #convert user input to hex in little endian
sum = hex(int('0xFFFFFFFF', 16) - int(num_tot, 16)) #substract same hex to "0xFFFFFFFF"

EDIT

More simply i want to combine 4bytes :

data = ["0xD0070000", "0x2FF8FFFF", "0xD0070000", "0x0AF50AF5"]

final result I want "0xD00700002FF8FFFFD00700000AF50AF5"

python
math
hex
asked on Stack Overflow Apr 13, 2019 by Martin.G • edited Apr 13, 2019 by Martin.G

1 Answer

0

Try this:

data = ["0xD0070000", "0x2FF8FFFF", "0xD0070000", "0x0AF50AF5"]
output = hex(int(data[0], 16) << 96 | int(data[1], 16) << 64 | int(data[2], 16) << 32 | int(data[3], 16) << 0)

output should become 0xd00700002ff8ffffd00700000af50af5

In some cases you won't get the output you expect because leading zeros will be chopped off, in that case you can fill the zeros manually doing:

print(f"0x{output[2:].zfill(32)}") # Uses f-string (requires newer python versions)

or

print("0x{}".format(output[2:].zfill(32))) # uses the old python format's string method
answered on Stack Overflow Apr 14, 2019 by BPL • edited Apr 14, 2019 by BPL

User contributions licensed under CC BY-SA 3.0