SMALLTALK LAB
Build and decode binary-reflected Gray codes
Order binary words so neighboring entries differ in exactly one bit. Construct the order by reflection, derive a compact XOR formula, decode it, and test the whole cycle.
Before you begin
Use a native Squeak Workspace. This lesson needs nonnegative Integers, Arrays and OrderedCollections. Select one complete checkpoint and choose Print it; all eight expressions are independent.
These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.
Expected values are Smalltalk expressions. The printer may show explicit Symbol markers: #(A B) and #(#A #B) represent the same array of Symbols.
01 - See why ordinary counting changes several bits
A three-bit counter moves from 011 to 100 when it goes from 3 to 4. XOR marks the changed bit positions: 111 is seven, so all three bits changed. Gray order solves a different problem: visit every fixed-width word while changing only one bit per step. These are encodings of positions, not error-correcting codes.
{3 bitXor: 4. 2 bitXor: 3}Expected: #(7 1)

Try it: Write 2 and 3 as 010 and 011. Their XOR is 001: only the rightmost position changed.
02 - Reflect a one-bit order
Start with the one-bit Gray sequence 0, 1. Keep it as the first half. Reverse it for the second half and add 2, which prefixes a leading one. The resulting two-bit words are 00, 01, 11, 10. Reflection makes the join differ only in the new leading bit.
| previous reflected |
previous := #(0 1).
reflected := OrderedCollection new.
reflected addAll: previous.
previous reversed do: [:word | reflected addLast: word + 2].
reflected asArrayExpected: #(0 1 3 2)

Try it: Check both the middle join, 01 to 11, and the closing edge, 10 to 00.
03 - Grow to any small width
The zero-bit sequence contains one empty word represented by zero. On each pass, append a reversed copy with the next bit set. The values are decimal Integers representing binary words; changing the printed base would not change the sequence.
| words mask grown |
words := #(0).
mask := 1.
1 to: 3 do: [:width |
grown := OrderedCollection new.
grown addAll: words.
words reversed do: [:word | grown addLast: word + mask].
words := grown asArray.
mask := mask * 2].
wordsExpected: #(0 1 3 2 6 7 5 4)

Try it: The eight entries cover 0 through 7 once. In particular, the order is not numerically sorted.
04 - Compute a word directly with XOR
For a nonnegative position n, binary-reflected Gray code is n XOR (n shifted right by one). In Squeak, bitShift: -1 shifts right. Parentheses make the inner shift explicit. The formula avoids constructing earlier words when you only need one position.
| gray |
gray := [:n | n bitXor: (n bitShift: -1)].
(0 to: 7) collect: [:n | gray value: n]Expected: #(0 1 3 2 6 7 5 4)

Try it: Evaluate the formula for position 4: binary 100 XOR 010 gives 110, or decimal 6.
05 - Test the one-bit cyclic adjacency rule
XOR of two different words has exactly one set bit precisely when it is positive and d bitAnd: (d - 1) is zero. The modulo operation wraps the last index back to the first. This tests the closing edge as well as consecutive entries.
| words differences |
words := (0 to: 7) collect: [:n | n bitXor: (n bitShift: -1)].
differences := (1 to: words size) collect: [:i |
(words at: i) bitXor: (words at: (i \\ words size) + 1)].
{differences. differences allSatisfy: [:d |
d > 0 and: [(d bitAnd: (d - 1)) = 0]]}Expected: {#(1 2 1 4 1 2 1 4). true}

Try it: Why require d > 0? Identical words give d = 0, which is not a one-bit change.
06 - Recover the original position
Decoding repeatedly XORs the Gray word with its shifted suffixes. Each right shift brings the next prefix contribution into alignment. For example Gray value 6 represents position 4, not position 6. The loop stops because the input is nonnegative and eventually shifts to zero.
| gray remaining position |
gray := 6.
remaining := gray.
position := 0.
[remaining > 0] whileTrue: [
position := position bitXor: remaining.
remaining := remaining bitShift: -1].
positionExpected: 4

Try it: Trace remaining as 6, 3, 1. The accumulator becomes 6, 5, 4.
07 - Check round trips and uniqueness
For a six-bit domain, generate all 64 words and decode each one. A Set independently checks that no word was repeated. Testing decode(encode(n)) = n also checks the interpretation of code words versus positions.
| words decode passed |
words := (0 to: 63) collect: [:n | n bitXor: (n bitShift: -1)].
decode := [:word | | remaining position |
remaining := word. position := 0.
[remaining > 0] whileTrue: [
position := position bitXor: remaining.
remaining := remaining bitShift: -1].
position].
passed := (0 to: 63) allSatisfy: [:n |
(decode value: (words at: n + 1)) = n].
{words asSet size. passed}Expected: #(64 true)

Try it: The collection indices begin at one; the encoded positions begin at zero. Keep the n + 1 conversion.
08 - Cross-check reflection against the formula
Build each width from zero through eight using reflection, then compare every position with the XOR formula. The zero-width case has one word; unlike positive widths it does not have a one-bit closing edge to itself. Exhaustive checks for small widths are useful, but they do not replace the reflection argument.
| words mask checks expected grown |
words := #(0). mask := 1. checks := 0.
0 to: 8 do: [:width |
expected := (0 to: (1 bitShift: width) - 1)
collect: [:n | n bitXor: (n bitShift: -1)].
words = expected ifFalse: [self error: 'Gray construction mismatch'].
checks := checks + words size.
grown := OrderedCollection new. grown addAll: words.
words reversed do: [:word | grown addLast: word + mask].
words := grown asArray. mask := mask * 2].
checksExpected: 511

Try it: The count is 1 + 2 + 4 + ... + 256. Increase the maximum width cautiously: the stored sequence doubles each pass.
Watch the computed states

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.
Reason about correctness and limits
Restrict positions and code words to nonnegative integers. If you promise a width w, require n < (1 bitShift: w). Negative integer shifts and representations do not model this finite unsigned domain. The snippets deliberately use known valid inputs rather than silently truncating them.
Reflection preserves one-bit adjacency inside each half. At the middle join the lower bits match and only the new leading bit differs. For positive widths, the final word and the first word also differ by that bit. A Gray code is not unique; this lesson uses the binary-reflected convention.
Listing every w-bit word takes 2 raised to w entries and therefore exponential storage. The XOR formula uses two integer bit operations for one word, but those operations are not constant-time for arbitrarily large integers. Decoding performs up to w shifts and XORs.
One-bit adjacency is useful when modeling encoders or enumerating states with minimal bit changes. It does not itself detect or correct transmission errors, and a software sequence does not establish hardware timing or safety properties.
Three practice challenges
Track the bit that changed
Return the changed-bit mask for every edge of the three-bit cycle.
Show solution
XOR each word with the next, wrapping at the end as checkpoint 5 does. The masks are #(1 2 1 4 1 2 1 4). Masks 1, 2 and 4 identify bit positions 0, 1 and 2.
Reject out-of-range positions
Add a guard to a fixed-width encoder for width 3.
Show solution
Before encoding, require an Integer n satisfying n >= 0 and n < (1 bitShift: 3). Signal an error for -1 or 8 instead of masking them silently. Then apply n bitXor: (n bitShift: -1).
Compare two ways to visit subsets
Treat each bit as membership of one of three items. What changes from one Gray word to the next?
Show solution
Exactly one item enters or leaves the subset, including at the closing edge. Ordinary numeric order can toggle several memberships. Gray order changes enumeration order, not the set of all eight subsets.
Continue learning
Integer Bitsets | Base Conversion | Hamming Code
Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.