构建Ben Eater 8位计算机:用加减法实现通用门的可行性问询
Great question—this is exactly the kind of low-level computing hack that makes Ben Eater's 8-bit build so satisfying to dig into! Let's break this down step by step.
核心思路:利用减法+条件跳转模拟逻辑运算
Since your machine has conditional jumps (and is thus Turing-complete), you don't need hardware logic gates—you can simulate any logical operation (including NAND, the universal gate) using only addition, subtraction, and the ALU's flag bits (carry/zero, which Ben's design includes).
第一步:用减法实现NOT操作
For 8-bit unsigned numbers, the bitwise NOT of a value x is simply 255 - x (since 0xFF is 8 bits of all 1s; subtracting each bit of x from 1 flips it). In Ben's machine, you can store 0xFF in a fixed RAM address, then compute NOT x with a subtraction instruction:
LDA x ; Load x into accumulator SUB 0x00 ; Subtract 0xFF (stored at address 0x00) STA not_x ; Store the result (NOT x)
If you're using two's complement, NOT x is also equivalent to -x - 1—which is just two subtraction operations (negate x via subtraction from 0, then subtract 1).
第二步:模拟AND操作(然后推导NAND)
NAND is just NOT (A AND B), so first we need to compute A AND B. Here's how to do that with only加减法 and conditional jumps:
- Initialize variables:
- Store a mask
M = 0x01(starts at the least significant bit) in RAM. - Initialize a result register/RAM location
R = 0. - Set a loop counter to 8 (since we're handling 8 bits).
- Store a mask
- Loop through each bit:
- Check if the current bit of
Ais 1: Subtract the maskMfromA. If there's no borrow (carry flag is set), the bit is 1. - Do the same check for
Band the maskM. - If both bits are 1, add the mask
Mto the resultR(sets that bit in the result to 1). - Shift the mask left by 1 (equivalent to
M = M + M, since binary left shift is multiplying by 2). - Decrement the loop counter; if it's not zero, jump back to the start of the loop.
- Check if the current bit of
- Compute NAND: Take the result
R(which isA AND B) and run it through the NOT operation we did earlier.
16字节RAM的可行性
Absolutely—this fits easily in 16 bytes of RAM. Here's how you'd allocate the space:
- 1 byte: Constant
0xFF(for NOT operations) - 1 byte: Mask
M - 1 byte: Result
R - 1 byte: Loop counter
- Remaining 12 bytes: Program code (Ben's instructions are mostly 2 bytes each—opcode + address—so that's enough for 6+ instructions, which covers the loop, checks, and arithmetic operations)
Since Ben's machine has dedicated registers (accumulator, B register, program counter), you don't need to store input values A and B in RAM unless you want to preserve them—you can keep them in registers during the computation.
The key here is that Turing-completeness means you can simulate any computation with a small set of primitive operations (here, add/subtract + conditional jumps), even if you don't have hardware logic gates. The 16-byte limit is more than enough for this small logic simulation routine.
内容的提问来源于stack exchange,提问作者rjm27trekkie

