Java Integer.ParseInt translation to python

Nick Craig-Wood nick at craig-wood.com
Wed Feb 9 05:31:23 EST 2005


jose isaias cabrera <jicman at cinops.xerox.com> wrote:
[java output]
>  StringLength = 40
>  c1 193 -63
>  7c 124 124
>  e1 225 -31
>  86 134 -122
>  ab 171 -85
>  94 148 -108
>  ee 238 -18
>  b0 176 -80
>  de 222 -34
>  8a 138 -118
>  e3 227 -29
>  b5 181 -75
>  b7 183 -73
>  51 81 81
>  a7 167 -89
>  c4 196 -60
>  d8 216 -40
>  e9 233 -23
>  ed 237 -19
>  eb 235 -21
>  [B at 1616c7
> 
>  But, here is what I have for python,
> 
>  def PrepareHash(HashStr):
>    while len(HashStr) > 0:
>      byte = HashStr[0:2]
>      print byte,int(byte,16),byte(int(byte,16)) # & 0xff
>      HashStr = HashStr[2:]
>    return byte
> 
>  def Main():
>    HashStr = "c17ce186ab94eeb0de8ae3b5b751a7c4d8e9edeb"
>    HashStr = PrepareHash(HashStr)
>    print "Prepared HashStr :",HashStr
> 
>  Main()

When I try your code I get this...

>>> def PrepareHash(HashStr):
...     while len(HashStr) > 0:
...             byte = HashStr[0:2]
...             print byte,int(byte,16),byte(int(byte,16)) # & 0xff
...             HashStr = HashStr[2:]
...     return byte
... 
>>> HashStr = "c17ce186ab94eeb0de8ae3b5b751a7c4d8e9edeb"
>>> print PrepareHash(HashStr)
c1 193
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in PrepareHash
TypeError: 'str' object is not callable
>>> 

You cant do byte(int(byte,16)) - byte is a string!  So you haven't
posted the actual code you ran...

Anyway what you want is this

>>> decoded = HashStr.decode('hex')
>>> for i,c in enumerate(decoded): print "%2d %02x" % (i,ord(c))
... 
 0 c1
 1 7c
 2 e1
 3 86
 4 ab
 5 94
 6 ee
 7 b0
 8 de
 9 8a
10 e3
11 b5
12 b7
13 51
14 a7
15 c4
16 d8
17 e9
18 ed
19 eb

>  and it results to,
> 
>  mulo 19:32:06-> python test.py
>  c1 193 Á
>  7c 124 |
>  e1 225 á
>  86 134
>  ab 171 «
>  94 148
>  ee 238 î
>  b0 176 °
>  de 222 Þ
>  8a 138
>  e3 227 ã
>  b5 181 µ
>  b7 183 ·
>  51 81 Q
>  a7 167 §
>  c4 196 Ä
>  d8 216 Ø
>  e9 233 é
>  ed 237 í
>  eb 235 ë
> 
>  which is not even close, and yes, I know that it's not the same
>  code.

Actually the hex digits are the same in all 3 cases, so the strings
are the same.  The reason the characters look different is because
you've got a different encoding for the python and java output I would
guess.

Java bytes are signed also just to add to the confusion.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list