在Python中将字符串转换为十六进制

时间:2017-05-18 12:43:26

标签: python struct binascii

这是我从数组构建消息的函数。 有两种类型的检查:

  
      
  • 检查" C"," G"," A" - > [(" {' chip_id':' 00012345',' check_type':' C'}",1494273855.0) ]

  •   
  • 检查" P" - > [" {'纬度':43.5529109,'经度':1.4910036,'检查类型':' P'}&# 34;,1494273855.0]

  •   
    def build(self, checks):
    #checks is an array.
    # #1- On transforme notre check en tuple
    _tuple = checks[0]
    #2- On recupere le couple id/type en string. On recupere le timestamp en string
    _type = _tuple[0]
    _timestamp = _tuple[1]
    #Selection taille message d apres le type element
    e = _type.find("type': '")
    type = _type[e+8]
    if type == "C" or type == "A" or type == "G":
        start = _type.find("'chip_id': '")
        stop = _type.find("', '")
        chip_id = _type[start + 12:stop]
        a = int(binascii.hexlify(chip_id))
        msg_build = bytes(type) + hex(int(_timestamp)) + hex(struct.unpack('<I', struct.pack('<f', a))[0]) + bytes(b"P")
    if type == "P":
        start_lat = _type.find("'latitude': ")
        end_lat =  _type.find(", 'long")
        latitude = float(_type[start_lat+12:end_lat])
        start_long = _type.find("'longitude': ")
        end_long = _type.find(", 'chec")
        longitude = float(_type[start_long+13:end_long])
        msg_build = bytes(type) + hex(int(_timestamp)) + hex(struct.unpack('<I', struct.pack('<f', latitude))[0]) +  hex(struct.unpack('<I', struct.pack('<f', longitude))[0])
    return msg_build

使用此功能,我可以将任何检查转换为所需的消息。它似乎工作得很好。

  

&#34; C&#34; check_type返回消息,如&#34; C0x5910e6b80x592c40b7P&#34;。

     

&#34; P&#34; check_type返回消息,如&#34; P0x5910ca4b0x420f12d00x428fca07&#34;

但是,在另一方面,我需要解密这些消息并获取所有信息。我可以为我的&#34; P&#34;消息。

对于check_type&#34; C&#34;当我需要解密时,我遇到了一些问题。

让我们举一个例子,我将构建以下检查:

  

[(&#34; {&#39; chip_id&#39;:&#39; 00014876&#39;,&#39; check_type&#39;:&#39; C&#39;}&#34; ,1494279864.0)]

&#34; chip_id&#34;总是8位数,&#34; check_type&#34;将是&#34; C&#34;,&#34; G&#34;或&#34; A&#34; (这在这里并不重要)和时间戳。

我的功能返回:

  

C0x5910e6b80x592c40b7P

  • C是我的类型。
  • 0x5910e6b8是我的时间戳。如果我做&#34; int(&#34; 0x5910e6b8&#34;,0)&#34;,我发现&#34; 1494279864&#34;检查中的时间戳
  • 0x592c40b7是我的chip_id。

那是我的问题。 我可以用:

加密我的chip_id
  • a = int(binascii.hexlify(chip_id))
  • hex(struct.unpack('<I', struct.pack('<f', a))[0])

但是,我无法找到如何从加密消息中的十六进制(&#34; 0x592c40b7&#34;)中获取我的chip_id(&#34; 00012345&#34;)。

有人知道我该怎么做吗?

1 个答案:

答案 0 :(得分:0)

这是否符合要求:

msg = ''.join(["{:02X}".format(e) for e in bytearray("Hello, world!")])
''.join([chr(int(msg[i:i+2], 16)) for i in range(0, len(msg), 2)])