Jump to content

Gray code: Difference between revisions

Add BASIC
(Add BCPL)
(Add BASIC)
Line 1,159:
30 => 11110 => 10001 => 11110
31 => 11111 => 10000 => 11111</pre>
 
=={{header|BASIC}}==
<syntaxhighlight lang="gwbasic">10 DEFINT A-Z
20 FOR I=0 TO 31
30 N=I:GOSUB 200:E=R:REM Encode
40 N=E:GOSUB 300:D=R:REM Decode
50 N=I:GOSUB 400:I$=R$:REM Binary format of input
60 N=E:GOSUB 400:E$=R$:REM Binary format of encoded value
70 N=D:GOSUB 400:D$=R$:REM Binary format of decoded value
80 PRINT USING "##: \ \ => \ \ => \ \ => ##";I;I$;E$;D$;D
90 NEXT
100 END
200 REM Gray encode
210 R = N XOR N\2
220 RETURN
300 REM Gray decode
310 R = N
320 N = N\2
330 IF N=0 THEN RETURN
340 R = R XOR N
350 GOTO 320
400 REM Binary format
410 R$ = ""
420 R$ = CHR$(48+(N AND 1))+R$
430 N = N\2
440 IF N=0 THEN RETURN ELSE 420</syntaxhighlight>
{{out}}
<pre> 0: 0 => 0 => 0 => 0
1: 1 => 1 => 1 => 1
2: 10 => 11 => 10 => 2
3: 11 => 10 => 11 => 3
4: 100 => 110 => 100 => 4
5: 101 => 111 => 101 => 5
6: 110 => 101 => 110 => 6
7: 111 => 100 => 111 => 7
8: 1000 => 1100 => 1000 => 8
9: 1001 => 1101 => 1001 => 9
10: 1010 => 1111 => 1010 => 10
11: 1011 => 1110 => 1011 => 11
12: 1100 => 1010 => 1100 => 12
13: 1101 => 1011 => 1101 => 13
14: 1110 => 1001 => 1110 => 14
15: 1111 => 1000 => 1111 => 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>
 
=={{header|Batch File}}==
2,114

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.