Death_Dealer
Death_Dealer

Reputation: 335

Python 3 struct.pack not formatting hex string correctly

   #res\file_1.png- file_1

    file_1_size_bytes = len(file_1_read)

    print (("file_1.png is"),(file_1_size_bytes),("bytes."))

    struct.pack( 'i', file_1_size_bytes)
    file_1_size_bytes_hex = binascii.hexlify(struct.pack( '>i', file_1_size_bytes))
    print (("Hexlifyed length - ("),(file_1_size_bytes_hex),(")."))

    with open(pack, 'ab') as header_1_:
    header_1_.write(binascii.unhexlify(file_1_size_bytes_hex))

    print (("("),(binascii.unhexlify(file_1_size_bytes_hex)),(")"))

    with open(pack, 'ab') as header_head_1:
    header_head_1.write(binascii.unhexlify("000000"))
    print ("Header part 2 added.")
    print ("file_1.png byte length added to header.")

    print ("-------------------------------------------------------------------------------") 



    #res\file_2.png- file_2

    file_2_size_bytes = len(file_2_read)

    print (("file_2.png is"),(file_2_size_bytes),("bytes."))

    struct.pack( 'i', file_2_size_bytes)
    file_2_size_bytes_hex = binascii.hexlify(struct.pack( '>i', file_2_size_bytes))
    print (("Hexlifyed length - ("),(file_2_size_bytes_hex),(")."))

    with open(pack, 'ab') as header_2_:
    header_2_.write(binascii.unhexlify(file_2_size_bytes_hex))

    print (("("),(binascii.unhexlify(file_2_size_bytes_hex)),(")"))

    with open(pack, 'ab') as header_head_2:
    header_head_2.write(binascii.unhexlify("000000"))
    print ("Header part 3 added.")
    print ("file_2.png byte length added to header.")

    print ("-------------------------------------------------------------------------------") 

file_1.png is 437962 bytes.
Hexlifyed length - ( b'0006aeca' ).
( b'\x00\x06\xae\xca' )
Header part 2 added.
file_1.png byte length added to header.
-------------------------------------------------------------------------------
file_2.png is 95577 bytes.
Hexlifyed length - ( b'00017559' ).
( b'\x00\x01uY' )
Header part 3 added.
file_2.png byte length added to header.
-------------------------------------------------------------------------------

For some reason the struct.pack doesnt format file_2 properly. it should print "( b'\x00\x01\x75\x59' )". but instead prints "( b'\x00\x01uY' )". Any idea what might be going on here? its telling me post more information to be eligible post the my question. so im just going to type random stuff until it lets me post my question.

Upvotes: 0

Views: 1002

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 178379

Change your expectations :)

>>> b'\x75' == b'u'
True
>>> b'\x59' == b'Y'
True

The two strings are equivalent. Python displays ASCII characters in byte strings:

>>> b'\x00\x01\x75\x59' == b'\x00\x01uY'
True

These are just printable representations of the same byte string. Both objects contain the same byte values:

>>> list(b'\x00\x01uY')
[0, 1, 117, 89]
>>> list(b'\x00\x01\x75\x59')
[0, 1, 117, 89]

Upvotes: 2

Related Questions