hexadecimal string to byte array in python

前端 未结 8 1982
孤城傲影
孤城傲影 2020-11-22 11:53

I have a long Hex string that represents a series of values of different types. I wish to convert this Hex String into a byte array so that I can shift each value out and co

8条回答
  •  我在风中等你
    2020-11-22 12:31

    Assuming you have a byte string like so

    "\x12\x45\x00\xAB"

    and you know the amount of bytes and their type you can also use this approach

    import struct
    
    bytes = '\x12\x45\x00\xAB'
    val = struct.unpack('

    As I specified little endian (using the '<' char) at the start of the format string the function returned the decimal equivalent.

    0x12 = 18

    0x45 = 69

    0xAB00 = 43776

    B is equal to one byte (8 bit) unsigned

    H is equal to two bytes (16 bit) unsigned

    More available characters and byte sizes can be found here

    The advantages are..

    You can specify more than one byte and the endian of the values

    Disadvantages..

    You really need to know the type and length of data your dealing with

提交回复
热议问题