Valhalla Legends Forums Archive | Java Programming | Unsigned division in Java

AuthorMessageTime
iago
After much pondering, I figured it out. It's a little messy, but isn't all that bad:
[code] public static int Divide(int a, int b)
{
long c = a;
long d = b;

c = c & 0xFFFFFFFFl;
d = d & 0xFFFFFFFFl;

long lResult = (long)c / (long)d;

return (int)(lResult & 0xFFFFFFFFl);
}[/code]

Which can be shortened to this:
[code] public static int Divide(int a, int b)
{
// Basically, we treat them as longs then mask out the sign-
// extension.
return (int)(((long) a & 0xFFFFFFFFl) / ((long) b & 0xFFFFFFFFl));
}[/code]


[edit] Fixed a line break that vi added
[edit2] Fixed a small glitch with the second program
November 21, 2003, 6:05 PM
St0rm.iD
+a million
November 21, 2003, 8:17 PM
iago
I'm wondering what kp will say, mostly :)
November 21, 2003, 8:19 PM
Kp
[quote author=iago link=board=5;threadid=3741;start=0#msg30547 date=1069445946]
I'm wondering what kp will say, mostly :)[/quote]

If you wanted unsigned division, why are you using Java? :P
November 21, 2003, 8:31 PM
iago
[quote author=Kp link=board=5;threadid=3741;start=0#msg30550 date=1069446712]
[quote author=iago link=board=5;threadid=3741;start=0#msg30547 date=1069445946]
I'm wondering what kp will say, mostly :)[/quote]

If you wanted unsigned division, why are you using Java? :P
[/quote]

I did it in a fairly clean way, though!
November 21, 2003, 10:39 PM
Adron
I noted before that you can do unsigned multiply and divide by using signed numbers with > twice the bits.
November 22, 2003, 2:23 AM
iago
I don't remember you noting that, but it's fairly logical if you think about it.
November 22, 2003, 3:32 AM
Adron
Yes. What you have to be careful about is that you need 64-bit signed numbers to handle 16-bit unsigned, unless there's some trick I missed.
November 22, 2003, 3:44 AM

Search