file_1 = (r'res\test.png')
with open(file_1, 'rb') as file_1_:
file_1_read = file_1_.read()
file_1_hex = binascii.hexlify(file_1_read)
print ('Hexlifying test.png..')
file_1_size_bytes = len(file_1_read)
file_1_size_bytes_hex = binascii.hexlify(file_1_size_bytes)
print (file_1_size_bytes_hex)
TypeError: 'int' does not support the buffer interface
Ok so im trying to hexlify the .png's byte length here. i know its because the len() of file_1_read is a number. im trying to convert decimal to hexidecimal. how would i go about doing that?
You can use str.format
with x
type:
>>> '{:x}'.format(123)
'7b'
>>> '{:08x}'.format(123)
'0000007b'
or using printf
-style formatting:
>>> '%x' % 123
'7b'
>>> '%08x' % 123
'0000007b'
If you want to use binascii.hexlify
, convert the int
object to bytes
using struct.pack
:
>>> import struct
>>> import binascii
>>> struct.pack('i', 123) # Replace 123 with `file_1_size_bytes`
b'{\x00\x00\x00'
>>> binascii.hexlify(struct.pack('i', 123))
b'7b000000'
You can control byte order using >
, <
, .. format specifier:
>>> binascii.hexlify(struct.pack('>i', 123))
b'0000007b'
>>> binascii.hexlify(struct.pack('<i', 123))
b'7b000000'
See Format characters - python struct
module documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With