Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Mathematics beyond the 31-bit barrier

Status
Not open for further replies.

sophisticate

Programmer
Aug 2, 2000
227
US
Hello!

I am wondering if anyone has been able to figure out how to do math beyond 31-bits and keep the variable type as an int. Here's the problem:

I'm working on an IPV4 class that allows binary manipulation of addresses. IP addresses are 32-bit (each a in a.a.a.a is an 8 bit number (256 possibilities)), so consequently, 31-bit numbers do not suffice. I can do the math with the BCMath module, but when I try to convert to binary format for printing or storage, I end up with 0111 1111 1111 1111 1111 1111 1111 1111. The only thing I can come up with is to separate both the original number and adder into 16- or 8- or 4- bits then combine them in a string for storage, but that's a massive headache and I don't have the endless supply of Advil it would require. So I was wondering if there was a more efficient way that anyone has found.

If my question is unclear, it's because it's 6am and I haven't made it to bed yet... but if you think you might know and just need some additional clarification, feel free to e-mail me.

Thanks,

brendanc@icehouse.net
 
What do you mean convert for printing or storage? How are you printing, and how are you storing, in a database, as files? Is this in Unix, or Win32?

And I'm not sure why it's such a headache to split the numbers, either.

Maybe if you showed some of the relevant code I could help.
 
I shouldn't have said printing nor storage. I actually want to keep the numbers in binary format for further mathematical operations such as bit masking and other subnet calculations.

I figured it out by splitting the address into two 16 bit numbers, and it wasn't the headache I expected. I simply mod 65536 the int address (using BCMath), store that as the low word, then subtract the low word from the initial number, right shift 16 and store that as the high word. So I guess this question is null, unless anyone wants to suggest how to maintain 32 bit numbers for efficiency.

Thanks,

brendanc@icehouse.net
 
Oh, for those interested in this kind of thing, I should include the following:

The shift right I mention above might lend some confusion because it's still a 32-bit number I'm working with and the BCMath functions don't allow for shifts. But each shift right is equal to dividing by two, so executing a bcdiv(x,2) then a >>=15 yields the correct result. bcdiv(x,65536) would result in the same thing, I think, but the bit shifting is typically more efficient.

brendanc@icehouse.net
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top