String to hexadecimal conversion

John Machin sjmachin at lexicon.net
Mon Sep 8 05:31:30 EDT 2008


On Sep 8, 7:05 pm, Praveena P <praveenapa... at gmail.com> wrote:
> Hi folks,
>
> I am new to Python... so am not too sure about how the type conversion
> works.
>
> I have to read a file that contains hexadecimal data and use the data
> further to do some arithmetic calculations.
> A sample of the input is : 00000000000020E0000032F800000000400022005E
> The problem I am facing is this:
> I am using f.read(2) to read a byte at a time, but the data that is
> read is a string rather than a number. So it kind of hampers any
> arithmetic operations I perform on this data...
>
> Could you please suggest some method I could use for this?

*IF* all the data consists of unsigned 8-bit integers
a_byte = f.read(2)
uint8 = int(a_byte, 16)

But I doubt it and that would be rather slow anyway. If your data is
homogenous, look at the array module. Otherwise, once you've worked
out how to break your file down into records, and what the layout of
each record is, you'll need the struct module.

HTH,
John



More information about the Python-list mailing list