Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexlify an integer in Python

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?

like image 322
Death_Dealer Avatar asked Sep 04 '25 16:09

Death_Dealer


1 Answers

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

like image 57
falsetru Avatar answered Sep 07 '25 18:09

falsetru