0

I have a Unicode character that is initially comes from the network as "abcd", I had to convert it to HEX representation (converting each byte separately to hex) and now it looks like "61626364". How to I convert it from little endian to big endian? The existing code does this: where hexval is "61626364"

       little_endian = hexval[:2]
    big_endian = hexval[-2:]

    hexval = big_endian + little_endian

but when I do it on Interactive Command Line it shows the result of "6461"... I guess it is because the hexval is string so it take 2 chars. So then I convert the string to byte array:

res = bytes(hexval, 'utf-8')

then res becomes b'61626364', and if I do

le = res[:2]
be - res[-2]
hexval = be + le

It still gives me b'6461' Basically second and third bytes are not participating (62 and 63 bytes)

Leon
  • 165
  • 12

1 Answers1

1

you should use struct to unpack bytes

import struct
# you can specify endianness with > or <
bytes2int = struct.unpack(">I",b'abcd')[0]
# convert to hex to print 0x61626364
print(hex(bytes2int))

if you have a string instead of bytes... it should only consist of 0-F and so should be very safe to do my_bytes=my_str.decode()

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179