Jump to content

Gray code: Difference between revisions

m (→‎{{header|XBasic}}: Added comment with title.)
Line 5,262:
30: 11110 => 10001 => 11110 : 30
31: 11111 => 10000 => 11111 : 31
</pre>
 
== {{header|TypeScript}} ==
{{trans|DWScript}}
<lang javascript>// Gray code
 
function encode(v: number): number {
return v ^ (v >> 1);
}
function decode(v: number): number {
var result = 0;
while (v > 0) {
result ^= v;
v >>= 1;
}
return result;
}
 
console.log("decimal binary gray decoded");
for (var i = 0; i <= 31; i++) {
var g = encode(i);
var d = decode(g);
process.stdout.write(
" " + i.toString().padStart(2, " ") +
" " + i.toString(2).padStart(5, "0") +
" " + g.toString(2).padStart(5, "0") +
" " + d.toString(2).padStart(5, "0") +
" " + d.toString().padStart(2, " "));
console.log();
}
</lang>
{{out}}
<pre>
decimal binary gray decoded
0 00000 00000 00000 0
1 00001 00001 00001 1
2 00010 00011 00010 2
3 00011 00010 00011 3
4 00100 00110 00100 4
5 00101 00111 00101 5
6 00110 00101 00110 6
7 00111 00100 00111 7
8 01000 01100 01000 8
9 01001 01101 01001 9
10 01010 01111 01010 10
11 01011 01110 01011 11
12 01100 01010 01100 12
13 01101 01011 01101 13
14 01110 01001 01110 14
15 01111 01000 01111 15
16 10000 11000 10000 16
17 10001 11001 10001 17
18 10010 11011 10010 18
19 10011 11010 10011 19
20 10100 11110 10100 20
21 10101 11111 10101 21
22 10110 11101 10110 22
23 10111 11100 10111 23
24 11000 10100 11000 24
25 11001 10101 11001 25
26 11010 10111 11010 26
27 11011 10110 11011 27
28 11100 10010 11100 28
29 11101 10011 11101 29
30 11110 10001 11110 30
31 11111 10000 11111 31
</pre>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.