Skip to content Skip to sidebar Skip to footer

Reverse Int As Hex

I have int in python that I want to reverse x = int(1234567899) I want to result will be 3674379849 explain : = 1234567899 = 0x499602DB and 3674379849 = 0xDB029649 How to do that i

Solution 1:

>>>import struct>>>struct.unpack('>I', struct.pack('<I', 1234567899))[0]
3674379849
>>>

This converts the integer to a 4-byte array (I), then decodes it in reverse order (> vs <).

Documentation: struct

Solution 2:

If you just want the result, use sabiks approach - if you want the intermediate steps for bragging rights, you would need to

  • create the hex of the number (#1) and maybe add a leading 0 for correctness
  • reverse it 2-byte-wise (#2)
  • create an integer again (#3)

f.e. like so

n = 1234567899# 1
h = hex(n)              
iflen(h) % 2:    # fix for uneven lengthy inputs (f.e. n = int("234",16))
    h = '0x0'+h[2:]
# 2 (skips 0x and prepends 0x for looks only)
bh = '0x'+''.join([h[i: i+2] for i inrange(2, len(h), 2)][::-1])
# 3
b = int(bh, 16)
print(n, h, bh, b)

to get

1234567899 0x499602db 0xdb029649 3674379849

Post a Comment for "Reverse Int As Hex"