Valhalla Legends Archive

Programming => General Programming => Java Programming => Topic started by: iago on November 21, 2003, 12:05 PM

Title: Unsigned division in Java
Post by: iago on November 21, 2003, 12:05 PM
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
Title: Re:Unsigned division in Java
Post by: Banana fanna fo fanna on November 21, 2003, 02:17 PM
+a million
Title: Re:Unsigned division in Java
Post by: iago on November 21, 2003, 02:19 PM
I'm wondering what kp will say, mostly :)
Title: Re:Unsigned division in Java
Post by: 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
Title: Re:Unsigned division in Java
Post by: iago on November 21, 2003, 04:39 PM
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!  
Title: Re:Unsigned division in Java
Post by: Adron on November 21, 2003, 08:23 PM
I noted before that you can do unsigned multiply and divide by using signed numbers with > twice the bits.
Title: Re:Unsigned division in Java
Post by: iago on November 21, 2003, 09:32 PM
I don't remember you noting that, but it's fairly logical if you think about it.
Title: Re:Unsigned division in Java
Post by: Adron on November 21, 2003, 09:44 PM
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.