error when porting C code to Python (bitwise manipulation)
Dan Stromberg
dstromberglists at gmail.com
Thu Jul 10 00:25:53 EDT 2008
On Wed, 09 Jul 2008 20:56:59 -0700, Jordan wrote:
> I am trying to rewrite some C source code for a poker hand evaluator in
> Python. Putting aside all of the comments such as just using the C
> code, or using SWIG, etc. I have been having problems with my Python
> code not responding the same way as the C version.
>
> C verison:
>
> unsigned find_fast(unsigned u)
> {
> unsigned a, b, r;
> u += 0xe91aaa35;
> u ^= u >> 16;
> u += u << 8;
> u ^= u >> 4;
> b = (u >> 8) & 0x1ff;
> a = (u + (u << 2)) >> 19;
> r = a ^ hash_adjust[b];
> return r;
> }
>
>
> my version (Python, hopefully ;)):
>
> def find_fast(u):
> u += 0xe91aaa35
> u ^= u >> 16
> u += u << 8
> u ^= u >> 4
> b = (u >> 8) & 0x1ff
> a = (u + (u << 2)) >> 19
> r = a ^ hash_adjust[b]
> return r
>
>
> As far as I understand the unsigned instructions in C just increase
> amount of bytes the int can hold, and Python automatically converts to
> longs which have infinite size when necessary, so I am not sure why I am
> getting different results.
>
> I assume that I am missing something fairly simple here, so help a n00b
> out if you can :)
>
> Thanks in advance,
>
> jnb
What business does a poker hand evaluator have doing that kind of bitwise
arithmetic? One problem with C is not the language itself, but the
culture of using bitwise tricks where they aren't really necessary.
Anyway, I believe in C unsigned bitwise arithmetic, when overflowing an
integer will simply throw away the bits that are "too big". So if python
is converting to a long when overflowing, that would cause a different
result right there.
You could try throwing in "&= 0xffffffff" all over the place if the C
code was written for a 32 bit unsigned int. unsigned int will usually be
32 or 64 bits these days. If it's a 64 bit unsigned int in C, it'd be
"&= 0xffffffffffffffff".
More information about the Python-list
mailing list