User:Talarus Luan/IntegerLog

From Second Life Wiki
< User:Talarus Luan
Revision as of 18:05, 10 July 2013 by Talarus Luan (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Fast way to get a base 2 log (aka the Most Significant Bit (MSB) position) of a 32-bit integer:

<lsl>integer IntegerLog(integer piData) {

   integer liMask;
   integer liShift;
   integer liMSB;
       
   for (liShift = 16, liMask = 0xFFFF0000, liMSB = 0;
        liShift > 0;
        liShift = liShift >> 1, 
            liMask = (liMask >> liShift) & ~liMask) {
            
       if ((liMask & piData) != 0) {
           liMSB += liShift;
           piData = piData >> liShift;
       }
   }
   return liMSB;

}</lsl>

Can be used to detect a potential integer math overflow for multiply:

<lsl>if ((IntegerLog(N1)+IntegerLog(N2) < 31)

   M = N1 * N2; // safe multiply

else

   llOwnerSay("Overflow!");</lsl>