User:Talarus Luan/IntegerLog: Difference between revisions
Jump to navigation
Jump to search
Talarus Luan (talk | contribs) Initial version |
Talarus Luan (talk | contribs) mNo edit summary |
||
| Line 21: | Line 21: | ||
Can be used to detect a potential integer math overflow for multiply: | Can be used to detect a potential integer math overflow for multiply: | ||
<lsl>if ((IntegerLog(N1)+IntegerLog(N2) < 31) | <lsl>if ((IntegerLog(N1)+IntegerLog(N2)) < 31) | ||
M = N1 * N2; // safe multiply | M = N1 * N2; // safe multiply | ||
else | else | ||
llOwnerSay("Overflow!");</lsl> | llOwnerSay("Overflow!");</lsl> | ||
Latest revision as of 23:16, 10 July 2013
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>