6502, 12 bytes (13 bytes if Apple II)
6502
The machine code assumes that a pair of zero page locations are connected to character input ($FE) and output (FF) hardware. Many 6502-based systems facilitate I/O in this fashion, albeit I/O address are usually not in zero page.
For simplicity, I used Py65, a 6502 microcomputer system simulator written in Python.
Here is a memory dump from Py65. You can load the following code anywhere in zero page such that it does not overlap $FE and $FF.
PC AC XR YR SP NV-BDIZC
6502: 0000 00 00 00 ff 00110010
.mem 0:b
0000: a9 21 85 ff a5 fe f0 fc 85 ff d0 f4
Running in a Windows command window, you can paste (Ctrl+V) any text you desire, or you can simply type. If typing, press Ctrl+J for a newline (same ASCII char). Press Ctrl+C to interrupt the processor and return to the Py65 command prompt.
Naturally, assembly code is easier to read.
PC AC XR YR SP NV-BDIZC
6502: 0000 00 00 00 ff 00110010
.d 00:0b
$0000 a9 21 LDA #$21
$0002 85 ff STA $ff
$0004 a5 fe LDA $fe
$0006 f0 fc BEQ $0004
$0008 85 ff STA $ff
$000a d0 f4 BNE $0000
For clarity, here is the assembly code in CBA65 format.
; ASSEMBLE:
; cba65 bangit
;
; LOAD/RUN
; python3 py65/monitor.py -i 00fe -o 00ff -l bangit.bin
; goto 0000
.FILES BIN=256
; I/O LOCATIONS
GETC .EQU $FE ; (1) MOVING PY65'S GETC TO ZP SHAVES 1 BYTE
PUTC .EQU $FF ; (1) MOVING PY65'S PUTC TO ZP SHAVES 2 BYTES
.ORG $0000
VROOM LDA #'!'
STA PUTC
VROOM2 LDA GETC
BEQ VROOM2
STA PUTC
BNE VROOM
.END
Apple II
The code above assumes a null indicates there is no input, so continues polling until a non-null value is returned.
For comparison, the Apple I and Apple II signals availability of a new character by setting bit 7 of the keyboard I/O address, which then needs to be cleared after fetching the character. On those systems, character I/O usually is performed by calling system monitor routines instead of accessing the hardware directly.
By calling RDKEY ($FD0C) and COUT ($FDED), the Apple II equivalent of the above can be coded in 13 bytes, and is runnable anywhere in RAM. Here is the code I ran in an Apple //e emulator, a2ix on Android 9.
Pressing Return has the same effect as a newline.
*300L
0300- A9 A1 LDA #$A1
0302- 20 ED FD JSR $FDED
0305- 20 0C FD JSR $FD0C
0308- 20 ED FD JSR $FDED
030B- F0 F3 BEQ $0300
Did you notice that instead of the normal ASCII value #$21 for the exclamation point, #$A1 is used instead? That's because sending standard ASCII values to COUT causes them to be displayed in "inverse mode," black on white. Displaying ASCII in normal white on black requires adding #$80 to the character value in the accumulator before calling COUT. Because RDKEY returns characters with the hi-bit set, assembly programs generally cleared the bit of the character to obtain its ASCII value before using it.
a\n
anda
, can we require that there are no trailing newlines? \$\endgroup\$" "
, is the output supposed to be "!" or "! !" \$\endgroup\$