Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem reading hex data from image - python automatically converts to a string

I am reading in an image one byte at a time with with read(1), and appending it to a list. The image data is all hex data. When I print out the list with the print function it is in the format '\xd7'

['\xd7', '\xd7', '\xd7', '\xd7', '\xd7', '\xd7', '\xd7',...]

The problem is that now I need to perform some calculations on this hex data, however, it is in string format, and this '\xd' string format isn't supported by any of the int or hex conversion functions in python. They require a '0xd7' or just a 'd7'.

Thanks for the help

like image 793
lheezy Avatar asked Mar 02 '26 00:03

lheezy


1 Answers

It's interpreting them as characters, so use ord to turn them into numbers. I.e. ord('\xd7') gives 215.

Also if you use Windows, or the program might have to run on Windows, make sure that you've got the file open in binary mode: open("imagefile.png","rb"). Makes no difference on other operating systems.

like image 126
Thomas K Avatar answered Mar 04 '26 14:03

Thomas K