After much pondering, I figured it out. It's a little messy, but isn't all that bad:
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);
}
Which can be shortened to this:
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));
}
[edit] Fixed a line break that vi added
[edit2] Fixed a small glitch with the second program
+a million
I'm wondering what kp will say, mostly :)
Quote from: iago on November 21, 2003, 02:19 PM
I'm wondering what kp will say, mostly :)
If you wanted unsigned division, why are you using Java? :P
Quote from: Kp on November 21, 2003, 02:31 PM
Quote from: iago on November 21, 2003, 02:19 PM
I'm wondering what kp will say, mostly :)
If you wanted unsigned division, why are you using Java? :P
I did it in a fairly clean way, though!
I noted before that you can do unsigned multiply and divide by using signed numbers with > twice the bits.
I don't remember you noting that, but it's fairly logical if you think about it.
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.