51 lines
803 B
Plaintext
51 lines
803 B
Plaintext
implement Gray;
|
|
|
|
include "sys.m"; sys: Sys;
|
|
print: import sys;
|
|
include "draw.m";
|
|
|
|
Gray: module {
|
|
init: fn(nil: ref Draw->Context, args: list of string);
|
|
# Export gray and grayinv so that this module can be used as either a
|
|
# standalone program or as a library:
|
|
gray: fn(n: int): int;
|
|
grayinv: fn(n: int): int;
|
|
};
|
|
|
|
init(nil: ref Draw->Context, args: list of string)
|
|
{
|
|
sys = load Sys Sys->PATH;
|
|
for(i := 0; i < 32; i++) {
|
|
g := gray(i);
|
|
f := grayinv(g);
|
|
print("%2d %5s %2d %5s %5s %2d\n", i, binstr(i), g, binstr(g), binstr(f), f);
|
|
}
|
|
}
|
|
|
|
gray(n: int): int
|
|
{
|
|
return n ^ (n >> 1);
|
|
}
|
|
|
|
grayinv(n: int): int
|
|
{
|
|
r := 0;
|
|
while(n) {
|
|
r ^= n;
|
|
n >>= 1;
|
|
}
|
|
return r;
|
|
}
|
|
|
|
binstr(n: int): string
|
|
{
|
|
if(!n)
|
|
return "0";
|
|
s := "";
|
|
while(n) {
|
|
s = (string (n&1)) + s;
|
|
n >>= 1;
|
|
}
|
|
return s;
|
|
}
|