GoMonkey
GoMonkey

Reputation: 361

How to reverse the byte order of a 4 byte constant in Python?

I am wondering on how to reverse the byte order on a 4 byte constant string (e.g 0x243F6A88->0x88 0x3F 0x6A 0x88). My current solution will do this: 0x243F6A88->886A3F240x. Here is the code I have so far:

value = "0x243F6A99"
joined = "".join(map(str.__add__, value[-2::-2] ,value[-1::-2]))
print(joined)

Any insight appreciated!

Upvotes: 1

Views: 1012

Answers (2)

qdongxu
qdongxu

Reputation: 414

for Python2:

value="243F6A99".decode('hex')
value=value[::-1]
print (value.encode('hex'))

for Python3:

value=bytes.fromhex("243F6A99")
value=value[::-1]
print(bytes.hex(value))

Upvotes: 2

Michael Butscher
Michael Butscher

Reputation: 10959

If you are sure that the string has exactly eight hex digits, then

value = "0x243F6A99"
joined = "0x" + "".join(map(str.__add__, value[-2:1:-2] ,value[-1:2:-2]))
print(joined)

should be enough.

Upvotes: 0

Related Questions