[Tutor] Low Level Reads

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 28 Apr 2001 13:59:49 -0700 (PDT)


On Sat, 28 Apr 2001, Justin Ko wrote:

>          Hey everyone,
>          I've got a question about reading from files. I'm working on a 
> module to read ID3v2 tags off of mp3 files. When I read data from the mp3 
> file, the data is returned as a string of hex. For instance...
> 
> 
>          >>> file = open("some.mp3")
>          >>> file.seek(0, 0)
>          >>> header = file.read(11)
>          >>> header
>          'ID3\x03\x00\x00\x00\x00\x0ejT'
>          >>>
> 
>          How can i perform the conversion from hex to base 10? More 
> specifically, I need to obtain base 10 values for header[3:5]. int() 
> doesn't seem to like hexadecimal values. Neither does str() or float()...


I thought that int() would be fairly happy with hexidecimal numbers.  
Let's check:

###
>>> int("0x03")
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 0x03 
###

You're right; int() doesn't appear to know how to work with hexidecimal.  
However, there's a more robust version of int() within the string module
called atoi()  ("ascii to integer"):


###
>>> import string
>>> print string.atoi.__doc__
atoi(s [,base]) -> int
 
Return the integer represented by the string s in the given
base, which defaults to 10.  The string s must consist of one
or more digits, possibly preceded by a sign.  If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal.  If base is 16, a preceding 0x or 0X is
accepted.
###

Let's try this out:

###
>>> string.atoi("0x03", 0)
3 
###

Ok, so string.atoi() looks like it will be more useful for you: it can
convert strings in a particular base, like hexidecimal, to integers.  Try
using string.atoi() instead.


Good luck!