On 03/24/2012 01:10 AM, Alex Hall wrote:
Thanks, the& (bitwise operator) trick seems to be promising. Should I still mod by 256? If so, could you explain why, since the value cannot exceed 127? Also, how does that work if a possible vlaue is 255, according to the documentation?
You top-posted, which loses all earlier context. Please put your response *after* whatever you're quoting.
I gave several possibilities; you should use whichever seems to make the code clearest to you. I think using a c_ubyte is the most straightforward. That has values from 0 to 255, so it'd match the documentation.
But if you're sticking with c_byte, you have a signed value. So the docs lie about the range being 0 to 255. Or maybe they're written for some other language. If you want to explicitly get the values 0 to 255, you can use the expression I provided, using modulo 256.
But the & operator doesn't care a bit. (no pun intended). You can use it on signed or on unsigned, or on unsigned modulo-ed data. No change.
This all assumes you're running on a twos-complement processor, like the Intel Pentium. If you're on ones-complement, half this stuff breaks, and the other half doesn't work very well. Bit twiddling is quite processor specific. Fortunately for us, the vast majority of machines these days use twos-complement.
One other thing: these problems are not specific to Python. I spent quite a while 15 years ago teaching a Java developer how to deal with similar issues. At that time at least, Java didn't even have unsigned bytes.
-- DaveA _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor