简体   繁体   English

Python编码问题

[英]Python Encoding Issues

I have data that I would like to decode from and its in Windows-1252 basically I send code to a socket and it sends it back and I have to decode the message and use IEEE-754 to get a certain value from it but I can seem to figure out all this encoding stuff. 我有要从Windows 1252中解码的数据,基本上我将代码发送到套接字,然后将其发送回去,我必须解码消息并使用IEEE-754从中获取特定值,但是我可以似乎找出所有这些编码的东西。 Here is my code. 这是我的代码。

def printKinds ():
    test = "x40\x39\x19\x99\x99\x99\x99\x9A"

    print (byt1Hex(test))
    test = byt1Hex(test).replace(' ', '')
    struct.unpack('<d', binascii.unhexlify(test))
    print (test)
printKinds()

def byt1Hex( bytStr ):
    return ' '.join( [ "%02X" % ord( x ) for x in bytStr ] )

So I use that and then I have to get the value from that.. But it's not working and I can not figure out why. 因此,我使用了它,然后必须从中获得价值。.但是它不起作用,我不知道为什么。

The current output I am getting is 我得到的当前输出是

struct.unpack('<d', binascii.unhexlify(data))
struct.error: unpack requires a bytes object of length 8

That the error the expected output I am looking for is 25.1 but when I encode it, It actually changes the string into the wrong values so when I do this: 我正在寻找的预期输出错误为25.1,但是当我对其进行编码时,它实际上将字符串更改为错误的值,因此在执行此操作时:

 print (byt1Hex(data))

I expect to get this. 我希望得到这个。

40 39 19 99 99 99 99 9A

But I actually get this instead 但是我实际上得到了这个

78 34 30 39 19 99 99 99 99 9A
>>> import struct
>>> struct.pack('!d', 25.1)
b'@9\x19\x99\x99\x99\x99\x9a'
>>> struct.unpack('!d', _) #NOTE: no need to call byt1hex, unhexlify
(25.1,)

You send, receive bytes over the network. 您通过网络发送,接收字节。 No need hexlify/unhexlify them; 不需要将它们混合/分离。 unless the protocol requires it (you should mention the protocol in the question then). 除非协议要求(除非您在问题中提到协议)。

You have: 你有:

test = "x40\x39\x19\x99\x99\x99\x99\x9A"

You need: 你需要:

test = "\x40\x39\x19\x99\x99\x99\x99\x9A"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM