Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #16774
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: Hints for writing bit-twiddling code in Python |
| Followup-To | gmane.comp.python.general |
| Date | 2011-12-07 09:21 +0100 |
| Organization | None |
| References | <4edee584$0$13933$c3e8da3$76491128@news.astraweb.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3373.1323246133.27778.python-list@python.org> (permalink) |
Followups directed to: gmane.comp.python.general
Steven D'Aprano wrote:
> I have some bit-twiddling code written in Java which I am trying to port
> to Python. I'm not getting the same results though, and I think the
> problem is due to differences between Java's signed byte/int/long types,
> and Python's unified long integer type. E.g. Java's >>> is not exactly
> the same as Python's >> operator, and a character coerced to a byte in
> Java is not the same as ord(char) in Python. (The Java byte is in the
> range -128...127, I think, while the ord in Python is in 0...255.)
>
> Can anyone point me to some good resources to help me port the Java code
> to Python?
>
> If it helps, the Java code includes bits like this:
>
> long newSeed = (seed & 0xFFFFFFFFL) * 0x41A7L;
> while (newSeed >= 0x80000000L) {
> newSeed = (newSeed & 0x7FFFFFFFL) + (newSeed >>> 31L);
> }
> seed = (newSeed == 0x7FFFFFFFL) ? 0 : (int)newSeed;
>
>
> which I've translated into:
>
> newseed = (seed & 0xFFFFFFFF)*0x41A7
> while (newseed >= 0x80000000):
> newseed = (newseed & 0x7FFFFFFF) + (newseed >> 31)
> seed = 0 if newseed == 0x7FFFFFFF else newseed & 0xFFFFFFFF
I think you need to take negative ints into account. Try adding
if seed & 0x80000000: # 2**31
seed -= 0x100000000 # 2**32, two's complement
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Hints for writing bit-twiddling code in Python Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-12-07 04:03 +0000 Re: Hints for writing bit-twiddling code in Python Dan Stromberg <drsalists@gmail.com> - 2011-12-06 22:08 -0800 Re: Hints for writing bit-twiddling code in Python Peter Otten <__peter__@web.de> - 2011-12-07 09:21 +0100 Re: Hints for writing bit-twiddling code in Python Serhiy Storchaka <storchaka@gmail.com> - 2011-12-07 11:33 +0200
csiph-web