Skip to content

Commit 32b3d97

Browse files
committed
Make log2 more readable
1 parent c8e9e3c commit 32b3d97

File tree

1 file changed

+28
-30
lines changed

1 file changed

+28
-30
lines changed

contracts/utils/math/Math.sol

Lines changed: 28 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -389,38 +389,37 @@ library Math {
389389
*/
390390
function log2(uint256 value) internal pure returns (uint256) {
391391
uint256 result = 0;
392-
uint256 isGt;
392+
uint256 exp;
393393
unchecked {
394-
isGt = boolToUint(value > 0xffffffffffffffffffffffffffffffff);
395-
value >>= isGt * 128;
396-
result += isGt * 128;
394+
exp = 128 * boolToUint(value > (1 << 128) - 1);
395+
value >>= exp;
396+
result += exp;
397397

398-
isGt = boolToUint(value > 0xffffffffffffffff);
399-
value >>= isGt * 64;
400-
result += isGt * 64;
398+
exp = 64 * boolToUint(value > (1 << 64) - 1);
399+
value >>= exp;
400+
result += exp;
401401

402-
isGt = boolToUint(value > 0xffffffff);
403-
value >>= isGt * 32;
404-
result += isGt * 32;
402+
exp = 32 * boolToUint(value > (1 << 32) - 1);
403+
value >>= exp;
404+
result += exp;
405405

406-
isGt = boolToUint(value > 0xffff);
407-
value >>= isGt * 16;
408-
result += isGt * 16;
406+
exp = 16 * boolToUint(value > (1 << 16) - 1);
407+
value >>= exp;
408+
result += exp;
409409

410-
isGt = boolToUint(value > 0xff);
411-
value >>= isGt * 8;
412-
result += isGt * 8;
410+
exp = 8 * boolToUint(value > (1 << 8) - 1);
411+
value >>= exp;
412+
result += exp;
413413

414-
isGt = boolToUint(value > 0xf);
415-
value >>= isGt * 4;
416-
result += isGt * 4;
414+
exp = 4 * boolToUint(value > (1 << 4) - 1);
415+
value >>= exp;
416+
result += exp;
417417

418-
isGt = boolToUint(value > 0x3);
419-
value >>= isGt * 2;
420-
result += isGt * 2;
418+
exp = 2 * boolToUint(value > (1 << 2) - 1);
419+
value >>= exp;
420+
result += exp;
421421

422-
isGt = boolToUint(value > 0x1);
423-
result += isGt;
422+
result += boolToUint(value > 1);
424423
}
425424
return result;
426425
}
@@ -495,24 +494,23 @@ library Math {
495494
uint256 result = 0;
496495
uint256 isGt;
497496
unchecked {
498-
isGt = boolToUint(value > 0xffffffffffffffffffffffffffffffff);
497+
isGt = boolToUint(value > (1 << 128) - 1);
499498
value >>= isGt * 128;
500499
result += isGt * 16;
501500

502-
isGt = boolToUint(value > 0xffffffffffffffff);
501+
isGt = boolToUint(value > (1 << 64) - 1);
503502
value >>= isGt * 64;
504503
result += isGt * 8;
505504

506-
isGt = boolToUint(value > 0xffffffff);
505+
isGt = boolToUint(value > (1 << 32) - 1);
507506
value >>= isGt * 32;
508507
result += isGt * 4;
509508

510-
isGt = boolToUint(value > 0xffff);
509+
isGt = boolToUint(value > (1 << 16) - 1);
511510
value >>= isGt * 16;
512511
result += isGt * 2;
513512

514-
isGt = boolToUint(value > 0xff);
515-
result += isGt;
513+
result += boolToUint(value > (1 << 8) - 1);
516514
}
517515
return result;
518516
}

0 commit comments

Comments
 (0)