s LearnSqueak.com

SMALLTALK LAB

Base conversion: build a number one digit at a time

Write an integer encoder using quotient and remainder, reverse the process with a positional fold, and test binary through hexadecimal in Squeak.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Know integer arithmetic, blocks and collections. We convert nonnegative integers to digit strings in bases 2 through 16. This is a value-to-text operation, not a change to the number itself.

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.

01 - Separate quotient and remainder

Integer quotient tells us how many full groups of the base fit. Remainder is the ungrouped part, and becomes the rightmost digit. The identity n = quotient * base + remainder explains the algorithm.

Independent Workspace expression - select all, then Print it
| n base |
n := 45. base := 2.
{n // base. n \\ base}

Expected: {22. 1.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Separate quotient and remainder
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Check 45 = 22*2+1. Try base 10 to obtain quotient 4 and remainder 5.

Download this checkpoint

02 - Collect low digits first

Repeated division removes the least significant digit at every iteration. These remainders are therefore produced in reverse reading order. Stop when the quotient is zero.

Independent Workspace expression - select all, then Print it
| n digits |
n := 45. digits := OrderedCollection new.
[n > 0] whileTrue: [
 digits add: n \\ 2.
 n := n // 2].
digits asArray

Expected: {1. 0. 1. 1. 0. 1.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Collect low digits first
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Read these from right to left: 101101 is binary 45.

Download this checkpoint

03 - Map a digit to a character

An alphabet allows bases above ten to use letters. Arrays and Strings are one-based in Squeak, so a numeric digit zero maps to position one.

Independent Workspace expression - select all, then Print it
| alphabet |
alphabet := '0123456789ABCDEF'.
{alphabet at: 1. alphabet at: 11. alphabet at: 16}

Expected: {$0. $A. $F.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Map a digit to a character
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The digit value 15 becomes F, not a two-character decimal string.

Download this checkpoint

04 - Build the reusable encoder

addFirst: inserts each new high digit at the front. Validate before dividing, and explicitly handle zero because its loop never runs. This teaching version favors clear assembly over optimal large-string performance.

Independent Workspace expression - select all, then Print it
| encode |
encode := [:number :base | | n out alphabet |
 (number isInteger and: [number >= 0])
  ifFalse: [Error signal: 'Use a nonnegative integer'].
 (base isInteger and: [base between: 2 and: 16])
  ifFalse: [Error signal: 'Base must be from 2 to 16'].
 alphabet := '0123456789ABCDEF'.
 n := number. out := OrderedCollection new.
 [n > 0] whileTrue: [
  out addFirst: (alphabet at: (n \\ base)+1).
  n := n // base].
 out isEmpty ifTrue: [out add: $0].
 String withAll: out].
encode value: 45 value: 2

Expected: '101101'

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Build the reusable encoder
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change the base to 16; the same integer is written 2D.

Download this checkpoint

05 - Handle zero and other bases

Zero has one digit. Sixteen needs two digits in base sixteen. The output uses uppercase A through F, which is our chosen notation rather than a change in numeric value.

Independent Workspace expression - select all, then Print it
| encode |
encode := [:number :base | | n out alphabet |
 (number isInteger and: [number >= 0])
  ifFalse: [Error signal: 'Use a nonnegative integer'].
 (base isInteger and: [base between: 2 and: 16])
  ifFalse: [Error signal: 'Base must be from 2 to 16'].
 alphabet := '0123456789ABCDEF'.
 n := number. out := OrderedCollection new.
 [n > 0] whileTrue: [
  out addFirst: (alphabet at: (n \\ base)+1).
  n := n // base].
 out isEmpty ifTrue: [out add: $0].
 String withAll: out].
{encode value: 0 value: 2. encode value: 16 value: 16. encode value: 255 value: 16}

Expected: {'0'. '10'. 'FF'.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Handle zero and other bases
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try 255 in base 10 and base 2.

Download this checkpoint

06 - Read a digit string back

A left fold multiplies the accumulated prefix by the base, then adds the next digit. This example deliberately supplies a known valid binary string; a public decoder must reject invalid digits.

Independent Workspace expression - select all, then Print it
| result |
result := 0.
'101101' do: [:c | result := result*2+(c asciiValue-$0 asciiValue)].
result

Expected: 45

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Read a digit string back
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: After reading 101, the accumulator is five. The next 1 makes eleven.

Download this checkpoint

07 - Round-trip a family of values

Squeak's Number reader accepts radix notation such as 2r101101. Use it as an independent oracle for our encoder across several bases and values. This test covers zero and boundaries between digit lengths.

Independent Workspace expression - select all, then Print it
| encode |
encode := [:number :base | | n out alphabet |
 (number isInteger and: [number >= 0])
  ifFalse: [Error signal: 'Use a nonnegative integer'].
 (base isInteger and: [base between: 2 and: 16])
  ifFalse: [Error signal: 'Base must be from 2 to 16'].
 alphabet := '0123456789ABCDEF'.
 n := number. out := OrderedCollection new.
 [n > 0] whileTrue: [
  out addFirst: (alphabet at: (n \\ base)+1).
  n := n // base].
 out isEmpty ifTrue: [out add: $0].
 String withAll: out].
#(2 3 8 10 16) allSatisfy: [:base |
 (0 to: 100) allSatisfy: [:n |
  (Number readFrom: (base printString, 'r', (encode value: n value: base)) readStream)=n]]

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Round-trip a family of values
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Add 1024 and 65535 to spot-check larger boundaries.

Download this checkpoint

08 - Reject a meaningless base

Base one would not reduce the quotient, so an unguarded loop could run forever. Reject it before starting. The test checks our precise message instead of treating any exception as success.

Independent Workspace expression - select all, then Print it
| encode |
encode := [:number :base | | n out alphabet |
 (number isInteger and: [number >= 0])
  ifFalse: [Error signal: 'Use a nonnegative integer'].
 (base isInteger and: [base between: 2 and: 16])
  ifFalse: [Error signal: 'Base must be from 2 to 16'].
 alphabet := '0123456789ABCDEF'.
 n := number. out := OrderedCollection new.
 [n > 0] whileTrue: [
  out addFirst: (alphabet at: (n \\ base)+1).
  n := n // base].
 out isEmpty ifTrue: [out add: $0].
 String withAll: out].
[encode value: 10 value: 1. false]
 on: Error do: [:e | e messageText = 'Base must be from 2 to 16']

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Reject a meaningless base
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Also reject negative numbers and fractional bases.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Base conversion: build a number one digit at a time native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

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

There are O(log_base(n)) digits for a positive integer. Repeated integer division determines them; the cost of large-integer arithmetic grows with the input size. addFirst: on OrderedCollection can move elements, so this clear version is not a claim of optimal string-building complexity.

Our contract excludes signs, fractions and bases outside 2–16. A negative value can be handled by recording a sign and encoding its magnitude, but do not silently apply this rule to arbitrary text.

Smalltalk radix literals are already available, for example 16rFF. The purpose here is to understand positional representation rather than replace the built-in reader.

Three practice challenges

Challenge 1

Why is the remainder always a valid digit?

Show solution

For a positive base and nonnegative n, remainder lies from zero through base minus one.

Challenge 2

How would you avoid repeated front insertion?

Show solution

Append low digits, then reverse the collection once before constructing the String.

Challenge 3

Why is binary 100000 equal to 32?

Show solution

Only the position with weight 2 raised to 5 is set; all lower position weights contribute zero.

Continue learning

Integer Bitsets | Euclidean Gcd | First Text

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.