4
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?

1
  • Maybe I am missing something, but what about hex? Integer in, hex-representation out. builtin and easy Commented Jan 17, 2015 at 13:41

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

8 Comments

struct.pack( 'i', file_1_size_bytes) binascii.hexlify(struct.pack_into( '>i', file_1_size_bytes)) print (file_1_size_bytes_hex) So i was trying to pack the variable,im getting pack_into expected offset argument. whats the offset?
oops: / sorry i wrote that wrong. i included the assignment and im getting the same struct.error pack_into expected offset argument.
@Death_Dealer, Use pack instead of pack_into. (pack_into accepts an addition buffer object as the second parameter) docs.python.org/3/library/struct.html#struct.pack_into
ok so that fixed that error, now im getting, file_test.write(file_1_size_bytes_hex) TypeError: must be str, not bytes.
@Death_Dealer, unpack it, then pack it: struct.pack('>H', *struct.unpack('>I', b'\x00\x00\x00\x11')). IOW, convert it to int, then repack it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.