Right Shift

From Second Life Wiki
Revision as of 03:05, 3 February 2008 by Dedric Mauriac (talk | contribs) (New page: {{LSL Header}} Here's a function to pass a signed 32 bit integer along with a value indicating how far to shift the bits. This method is primarily needed to shift bits for negative integer...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Here's a function to pass a signed 32 bit integer along with a value indicating how far to shift the bits. This method is primarily needed to shift bits for negative integers, as the regular bit shift operators work just fine for positive values.

RightShift.lsl

<lsl> // right shift doesn't work well for signed integers. // we essentially perform the operation as if it was // an unsigned integer. integer rightShift(integer value, integer bits) {

   // positive numbers are fine
   if(value >= 0)
       return value >> bits;
   // remove bit sign
   value = value ^ 0x80000000;
   
   // move bits
   value = value >> bits;
   
   // inject signed bit to new location
   value = value | (integer)(llPow(2, 31 - bits));
   
   return value;

} default {

   state_entry()
   {
       // output should be 268435449
       llSay(DEBUG_CHANNEL, (string)rightShift(-99, 4));
       // before: 1111 1111 1111 1111 1111 1111 1001 1101
       // after:  0000 1111 1111 1111 1111 1111 1111 1001
   }

}</lsl>