简体   繁体   中英

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. 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:

 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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