Page 1 of 1

Modulus

Posted: Mon Aug 17, 2009 3:49 pm
by DDastardly71
I am trying to do a simple math using Modulus on large double-precision
numbers and I'm encountering an error.

I'm trying to convert an IP address to an IP number and I'm getting an
error on the last part. It works fine on paper but not in code.


IP_Address To IP_Number
w = 202
x = 186
y = 13
z = 4

IP_Number = (w * (256 ^ 3)) + (x * (256 ^ 2)) + (y * 256) + z


IP_Number to IP_Address

w = int( IP_Number / (256 ^ 3) ) MOD 256
x = int( IP_Number / (256 ^ 2) ) MOD 256
y = int( IP_Number / 256 ) MOD 256 <-- Error
z = int( IP_Number ) MOD 256 <-- Error


According to Microsoft MOD will "round real values to integers, if required".
To get the correct value for 'z' I had to write a modified function for
MOD but that only works half of the time.

Using the MOD on a very large double-precision number causes an error.
I've tested it and a double-precision number can handle numbers as high as (256 ^ 140)'.

Posted: Mon Aug 17, 2009 5:11 pm
by burger2227
MOD returns the integer remainder of a division. If it returns 0, then the number can be evenly divided by integer division. \ is used for real integer division, but it eliminates any remainder if there is any.

You don't even need the INT function in your calculations and you really don't want to use remainder division in this case.

Substitute the / divisions to \ integer division.

Why are you dividing by 256 for z? you never multiplied it by 256 in the first place.

Posted: Tue Aug 18, 2009 4:54 pm
by DDastardly71
I just copied the formula verbatim from the web site that I got it from but it would make sense to divide by something, otherwise, you will get whatever big number ip_number is.

This is the part where I'm confused. How to isolate the value of z.

Second question:

How do I use MOD on double-precision numbers?

Posted: Tue Aug 18, 2009 9:15 pm
by Mentat
How do I use MOD on double-precision numbers?
If you wanted to have a double modulus 5, you could do:

Code: Select all

dim myDouble as double
dim answer as integer

answer = cInt(myDouble) mod 5 'Casts myDouble to integer first
or

Code: Select all

dim myInteger as integer
dim myDouble as double
dim answer as integer

myInteger = myDouble

answer = myInteger mod 5

Posted: Wed Aug 19, 2009 2:03 am
by burger2227
How do you determine z?

Easy, just subtract the other variable values from the total IP value.