Probably the key improvement here is the use of hexadecimal notation: 0xffffffff instead of the corresponding, “magic” decimal. As long as you are very careful to use unsigned arithmetic and specify bitmasks that are no larger than the integer-size you know that you are using, code like this ought to be transportable. (It might not be readable, heh, but it ought to be int-length agnostic.)
I would almost edit my comment to say, don’t use “arithmetic” at all when you are bit-twiddling, as in code like this:
$num = $num - 4294967296 if $num > 4294967295;
$num = $num + 4294967296 if $num < -2147483648;
And I recognize at least one of those numbers, -2147483648
, as an old, familiar 32-bit friend. I also detect the presence of signed arithmetic, dependent upon the thirty-first
bit being the sign-bit. I suggest that this code should be rewritten to use bit-masking operators ... and to do so, perhaps, in a very specific
way, as follows:
If you want to mash-off, say, all but the rightmost 31 bits of an integer quantity, you should take: qty := qty and ( not 0x7fffffff );. (I am not using Perl notation here, for clarity.) The subexpression, (not 0x7fffffff), will evaluate to an int in which all bits are 1 except for the rightmost 31 bits, and it will do so correctly no matter what the sizeof(int) may be.
So, I suggest that you need to go through code like this (fortunately, it is a small piece of code), work out what it is doing and then rewrite it. Construct a very thorough set of Test::More cases that you can run on both a 32-bit and a 64-bit system to prove that your rewrite is thoroughly correct.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||