473,651 Members | 2,861 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieving int from hex in a file.

Hi.

I have to open a binary file from an old computer and recover the
information stored (or at least try to). I use:

f=open('file.bi n','rb')
a=f.read()
f.close()

a in now a string full of hex representations in the form:

a[6]='\x14'
a[7]='\x20'

I would like to convert these hex representations to int, but this
(the most obvious way) doesn't seem to be working
>>q=a[6]
q
'\x14'
>>int(q,16)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int():
>>>
How can I do this?

Thanks
Jun 27 '08 #1
5 3602
En Mon, 28 Apr 2008 07:14:51 -0300, Filipe Teixeira <fi*******@gmai l.comescribió:
a in now a string full of hex representations in the form:

a[6]='\x14'
a[7]='\x20'

I would like to convert these hex representations to int, but this
(the most obvious way) doesn't seem to be working
>>>q=a[6]
q
'\x14'
>>>int(q,16)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int():
>>>>
Use ord(q)

pyhelp(ord)
Help on built-in function ord in module __builtin__:

ord(...)
ord(c) -integer

Return the integer ordinal of a one-character string.

py>

--
Gabriel Genellina

Jun 27 '08 #2
Filipe Teixeira wrote:
I have to open a binary file from an old computer and recover the
information stored (or at least try to). I use:
I would like to convert these hex representations to int, but this
If you want to do it efficiently have a look at the array module:
>>import os, array
a = array.array("B" )
filename = "/usr/bin/python"
a.fromfile(op en(filename, "rb"), os.path.getsize (filename))
a[10]
0
>>a[:10]
array('B', [127, 69, 76, 70, 2, 1, 1, 0, 0, 0])

Peter
Jun 27 '08 #3
Filipe Teixeira wrote:
Hi.

I have to open a binary file from an old computer and recover the
information stored (or at least try to). I use:

f=open('file.bi n','rb')
a=f.read()
f.close()

a in now a string full of hex representations in the form:

a[6]='\x14'
a[7]='\x20'

I would like to convert these hex representations to int, but this
(the most obvious way) doesn't seem to be working
>>>q=a[6]
q
'\x14'
>>>int(q,16)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int():

How can I do this?

Thanks
As you say you are trying to recover information from the old computer
are you sure you want to convert the data to it's integer representation ?
What I mean is in this case the string will contain the actual data read
from the file, not a hex representation. It's just the python displays
this data as '\x14'. BTW - are you sure it's displaying '\x20' from your
data as this should be a space character i.e. " ".

In the python interpreter try this:

mydata=""
for i in range(256):
mydata+=chr(i)
>mydata
This will show you the hex representation of the values in mydata that
it can't display however the string is not a string of "hex values" as
such, it contains the binary values 0-255.
Jun 27 '08 #4
>
Use ord(q)

pyhelp(ord)
Help on built-in function ord in module __builtin__:

ord(...)
ord(c) -integer

Return the integer ordinal of a one-character string.

py>

--
Gabriel Genellina
Thank you Gabriel. It fit's my purpose.

Jun 27 '08 #5
On 2008-04-28, Filipe Teixeira <fi*******@gmai l.comwrote:
Hi.

I have to open a binary file from an old computer and recover the
information stored (or at least try to). I use:

f=open('file.bi n','rb')
a=f.read()
f.close()

a in now a string full of hex representations in the form:

a[6]='\x14'
a[7]='\x20'
a is now a string of binary data. It doesn't contain a "hex
representation" of anything. Hex is a way of printing stuff on
paper or on a screen. Python doesn't store anything in hex.
I would like to convert these hex representations to int,
That's your mistake: you don't have hex data. Nothing is being
stored in hex in your example.
but this (the most obvious way) doesn't seem to be working
>>>q=a[6]
q
'\x14'
>>>int(q,16)
That converts a hex string into an integer, you've not got a
hex string. You have a string containing binary data.

"4A4B4C" is a hex string. It's 6 bytes long and contains the
ASCII characters '4' 'A' '4' 'B' '4' 'C'.

"\x4a\x4b\4 c" is just a three-byte long chunk of binary data.
It was _typed_ in hex, but it's stored in binary not in hex.
It's identical to "JKL".
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int():
>>>>

How can I do this?
You can use the struct module, or you can do it explicitly like
this:
>>a = 'abcdef\x12\x34 qwer'
n = (ord(a[6])<<8) | ord(a[7])
n
4660
>>hex(n)
'0x1234'
>>>
--
Grant Edwards grante Yow! When you get your
at PH.D. will you get able to
visi.com work at BURGER KING?
Jun 27 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1790
by: Chris Shipley | last post by:
I am trying to present a list of links on a page (Form) where each link opens a different picture gallery. I have the Form page which contains the links, a Gallery page, and several include files. Each include file displays a different gallery. Clicking on a link submits a value identifying the chosen gallery to the Gallery page. The Gallery page accepts the value from the Form page and uses it to call the appropriate include file. The...
1
1994
by: Roman Kagan | last post by:
Hi everyone, I am successful in retrieving the image from the table (.TIF), however, the retrieved file does not work. It looks like an image file - extension, size and all, but the image is not visible. Any ideas? I'm including the first few lines (image opened with Notepad) of the file below. Please, help. """""
0
1261
by: Kurt Ng | last post by:
Hi, y'all. I am working on retrieving file version info on a third party dll. I have used the FileVersionInfo class to retrieve all of the standard version information already such as FileMajorPart, FileMinorPart, etc. However, the one attribute that is most important to me right now is the custom one that the dll creator had added. This attribute appears in the "Other version information" listbox when I show the file properties in...
0
1700
by: hsifelbmur | last post by:
We are writing an app that automates printing of documents of different types. These documents are printed to PostScript files, not to a printer. The app uses shellExecute with the "printto" verb (and the Process class). This is a server app which requires that everything is done without user intevention. The problem is that we need to grab these PostScript files after they've been printed, for further processing. Is there a way to set the...
0
1249
by: kid4rilla | last post by:
I can successfully write the binary data to an image data type, and successfully retrieve it, but when I attempt to play the file in media player after retrieving it, I get the file type isn't supported. I must be losing something somewhere, but the byte lengths match up. Is there some encoding I need to do. Please take a look, and suggestions would be appreciated.
0
2059
by: Andy | last post by:
Hi All. I'm working for a company that has set out a guideline for retrieving data from a database. Nobody can explain to me the reason for the following. When retrieving a set of records from database to a VB.net app, they retrieve the database fields as a record set eg. "select name, suburb from myTable"
3
1758
by: EYIII | last post by:
Is it possible to retrieve the "created by" identity and "modified by" identity for a file (e.g. word doc, .pdf, report, etc) using .NET?
1
2987
by: ahammad | last post by:
This application opens a Word document for editing. I need to keep the file path of the Word document even after it has been closed. I tried using Word event handlers but I couldn't figure it out, so I came up with this solution: _Application wordAppBlank; CString idBlank("Word.Application"); BOOL statusBlank = wordAppBlank.CreateDispatch(idBlank); CString blankFilePath; _Document myDocBlank;
2
2236
by: shivapadma | last post by:
i have inserted the image into database using the following code String driverName = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/"; String dbName = "hibernatetutorial"; String userName = "root"; String password = "root";
34
2548
by: vpriya6 | last post by:
Hi guys, I am new to Ajax, xml and javascript. I want to know how can I retrieve data from xml and display in the html page? please help me out. suppose my xml file is customer.xml the code is below: <CUSTOMER>
0
8357
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8803
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8700
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8465
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8581
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5612
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4285
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2701
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1910
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.