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

mensanator at aol.com mensanator at aol.com
Wed Jul 11 19:46:23 CEST 2007


On Jul 11, 3:21 am, Vishal <vsapr... at gmail.com> wrote:
> On May 30, 1:31 pm, Peter Otten <__pete... at web.de> wrote:
>
>
>
>
>
> > Vishal wrote:
> > > 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()
>
> > 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
>
> Thanks Peter for the explanation. Actually what I want is:
>
> if Input is 0x0164, Output should be: 0000000101100100
> where each nibble is separated and the output appears in terms of '0's
> and '1's.
>
> Can I do that with this function binascii.unhexlify()???

You can with gmpy:

>>> import gmpy
>>> x = 0x0164
>>> s = gmpy.digits(x,2)      # convert to base 2
>>> y = '0'*(16-len(s)) + s   # pad to 16 bits
>>> y
'0000000101100100'


>
> Thanks and best regards,
> Vishal




More information about the Python-list mailing list