Home     |     .Net Programming    |     cSharp Home    |     Sql Server Home    |     Javascript / Client Side Development     |     Ajax Programming

Ruby on Rails Development     |     Perl Programming     |     C Programming Language     |     C++ Programming     |     IT Jobs

Python Programming Language     |     Laptop Suggestions?    |     TCL Scripting     |     Fortran Programming     |     Scheme Programming Language


 
 
Cervo Technologies
The Right Source to Outsource

MS Dynamics CRM 3.0

Python Programming Language

binascii.unhexlify ... not clear about usage, and output


Hi,

I have a file with a long list of hex characters, and I want to get a
file with corresponding binary characters

here's what I did:

>>> import binascii
>>> f1 = 'c:\\temp\\allhex.txt'
>>> f2 = 'c:\\temp\\allbin.txt'
>>> sf = open(f1, 'rU')
>>> df = open(f2, 'w')
>>> slines = sf.readlines()
>>> for line in slines:

...     x = line.rstrip('\n')
...     y = binascii.unhexlify(x)
...     df.write(y)
...

>>> df.close()
>>> sf.close()

But what I get is all garbage, atleast textpad and notepad show that
I tried doing it for only one string, and this is what I am seeing on
the interpreter:

>>> x
'0164'
>>> y

'\x01d'

I was expecting 'y' would come out as a string with binary
characters!!!

What am i missing here? Can someone please help.

Thanks and best regards,
Vishal

Your code is OK, but you have to open f2 in binary mode if your data is
truly binary (an image, say).

> But what I get is all garbage, atleast textpad and notepad show that
> I tried doing it for only one string, and this is what I am seeing on
> the interpreter:

>>>> x
> '0164'
>>>> y
> '\x01d'

> I was expecting 'y' would come out as a string with binary
> characters!!!

What are "binary characters"?

> What am i missing here? Can someone please help.

What /exactly/ did you expect? Note that "\x01d" and "\x01\x64" are just
different renderings of the same string chr(0x01) + chr(0x64).

Peter

Add to del.icio.us | Digg this | Stumble it | Powered by Megasolutions Inc