BitHacksImpl.mesa
Copyright © 1985 by Xerox Corporation. All rights reserved.
Louis Monier December 17, 1985 4:51:55 pm PST
DIRECTORY BitHacks;
BitHacksImpl: CEDAR PROGRAM
EXPORTS BitHacks =
BEGIN
Goodies
-- The arithmetic stuff that people always want
PowersOfTwo: ARRAY [0 .. 33] OF INT = [
1B, 2B, 4B, 1B1, 2B1, 4B1,
1B2, 2B2, 4B2, 1B3, 2B3, 4B3,
1B4, 2B4, 4B4, 1B5, 2B5, 4B5,
1B6, 2B6, 4B6, 1B7, 2B7, 4B7,
1B8, 2B8, 4B8, 1B8, 2B8, 4B8,
1B9, 2B9, 4B9, 1B10];
ODD: PUBLIC PROC [i: INT] RETURNS [BOOL] =
{RETURN [(i MOD 2 # 0)]};
EVEN: PUBLIC PROC [i: INT] RETURNS [BOOL] =
{RETURN [(i MOD 2 = 0)]};
-- Floor
Log2: PUBLIC PROC [n: INT] RETURNS [INT] = {
IF n<=0 THEN RETURN [0];
FOR i: NAT IN [0..33] DO
IF n<PowersOfTwo[i] THEN RETURN [i-1];
REPEAT
FINISHED => ERROR;
ENDLOOP;
};
NBits: PUBLIC PROC [n: INT] RETURNS [INT] = {
IF n<=0 THEN RETURN [0];
IF n=1 THEN RETURN [1];
FOR i: NAT IN [1..33] DO
IF PowersOfTwo[i]>=n THEN RETURN [i];
REPEAT
FINISHED => ERROR;
ENDLOOP;
};
TwoToThe: PUBLIC PROC [x: INT] RETURNS [INT] =
{RETURN[PowersOfTwo[x]]};
TwoToTheLog2: PUBLIC PROC [n: INT] RETURNS [INT] =
{RETURN [TwoToThe[Log2[n]]]};
XthBitOfN: PUBLIC PROC [x, n: INT] RETURNS [BOOL] =
Warning: bit 0 is the LOW order bit (lsb)
{RETURN [IF x<0 THEN FALSE ELSE (n/TwoToThe[x]) MOD 2 =1]};
END.