• Welcome to Valhalla Legends Archive.
 

Unsigned division in Java

Started by iago, November 21, 2003, 12:05 PM

Previous topic - Next topic

iago

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
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


Banana fanna fo fanna


iago

I'm wondering what kp will say, mostly :)
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


Kp

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
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

iago

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!  
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


Adron

I noted before that you can do unsigned multiply and divide by using signed numbers with > twice the bits.

iago

I don't remember you noting that, but it's fairly logical if you think about it.
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


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.