Re: Reading a binary file

Discussion in 'Python' started by Andrew Bennetts, Jun 26, 2003.

  1. On Thu, Jun 26, 2003 at 11:33:20AM +0200, Sorin Marti wrote:
    > Andrew Bennetts wrote:
    > >On Thu, Jun 26, 2003 at 10:01:06AM +0200, Sorin Marti wrote:
    > >
    > >>But now I need the hex values of the binary file.

    > >
    > >You can get the hex value of a 1-character string with hex(ord(char)),
    > >e.g.:
    > >
    > > >>> char = 'a'
    > > >>> hex(ord(char))

    > > '0x61'
    > >

    >
    > That is not exactly what I meant. I've found a solution (a is the binary
    > data):
    >
    > b = binascii.hexlify(a)
    >
    > For example it gives me C8 which is a HEX-Value. How to change this one
    > into a decimal? (The decimal should be 130, right?)


    I think you might be confused about how bytes and numbers are related. Have
    a look at this:

    >>> char = 'a'
    >>> ord(char)

    97
    >>> type(ord(char))

    <type 'int'>
    >>> type(hex(ord(char)))

    <type 'str'>

    So I'm guessing you don't really want the hex representation at all!

    A quick way to convert a string of bytes into the corresponding numerical
    values is:

    >>> s = 'hello'
    >>> map(ord, s)

    [104, 101, 108, 108, 111]

    or:

    >>> s = 'hello'
    >>> [ord(char) for char in s]

    [104, 101, 108, 108, 111]

    And again, I *strongly* suggest you look at the struct module -- I'm not
    sure what you're trying to do, but if you're trying to interpret binary data
    into numbers and things, it's almost certainly helpful:

    http://python.org/doc/current/lib/module-struct.html

    e.g.:

    >>> s = 'hello'
    >>> struct.unpack('5B', s)

    (104, 101, 108, 108, 111)

    -Andrew.
     
    Andrew Bennetts, Jun 26, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Neo
    Replies:
    0
    Views:
    485
  2. El Durango

    reading binary file.

    El Durango, Dec 8, 2004, in forum: Java
    Replies:
    1
    Views:
    7,589
    Gordon Beaton
    Dec 8, 2004
  3. Ron Eggler

    writing binary file (ios::binary)

    Ron Eggler, Apr 25, 2008, in forum: C++
    Replies:
    9
    Views:
    971
    James Kanze
    Apr 28, 2008
  4. Guest
    Replies:
    6
    Views:
    1,791
    Guest
    Apr 25, 2010
  5. Jim
    Replies:
    6
    Views:
    768
Loading...

Share This Page