惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Stack Overflow Blog
Stack Overflow Blog
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Announcements
Recent Announcements
Microsoft Security Blog
Microsoft Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
J
Java Code Geeks
D
DataBreaches.Net
U
Unit 42
P
Proofpoint News Feed
I
InfoQ
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
博客园 - Franky
博客园_首页
IT之家
IT之家
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Building an NES Emulator in C: Part 1 – Emulating the 650...
Benjamin Vachon · 2026-06-22 · via DEV Community

Over the course of a few posts, I will be constructing an NES emulator that will allow you to play NES ROMs. Today’s post is the first in this series, where I will be walking through the process of emulating the CPU the NES used, the MOS 6502.

STRUCTURE

The 6502 has 6 primary registers we need to emulate in our program.
The A register is the accumulator, which is 1 byte long
The X register is an index register, which is also 1 byte long
The Y register is another index register, also 1 byte long
The Program Counter is 2 bytes long, allowing for accessing 65536 memory locations
The Stack Pointer is 1 byte long, allowing a 256 byte stack
The P register is a status register that is 1 byte long, containing the CPU status flags
Below is the struct I used for the 6502

typedef struct {
    uint8_t A;
    uint8_t X;
    uint8_t Y;
    uint16_t pc;
    uint8_t S;
    uint8_t P;
}cpu_6502;

MEMORY

The 6502 can read up to 64kb of memory thanks to the 2 byte long program counter. For my implementation, the memory is just a simple uint8_t array declared like so:

uint8_t memory[65536] = {0};

This just implements an array of 65536 bytes that we will load programs into, that the CPU will then step through. However, we need to have a function that is able to decode the commands.

OPCODES

An opcode (operation code) is a number that represents an instruction for the CPU. The 6502 has 56 distinct (useful) opcodes I will be emulating today. A full list of the opcodes can be found in this handy little table. Since there are so many opcodes, I will not go through them all. The full code can be found in my GitHub repo here: https://github.com/benjaminavachon/6502-emulator
Here we can discuss a few of the operations so you can get a feel for what they do.

The first one we will discuss is very simple. It is LDA; it simply loads the piece of data after the opcode stored in memory into the A register and increments the program counter to the next memory address. A simple example of this would be:
LDA 0x05
This instruction loads the value 0x05 into the A register.

Next, another very simple instruction is TAX. This just copies the value of the A register to the X register. An example of this is simply:
TAX
That is all that is needed to execute this instruction.

The last one we will discuss is the JSR instruction. This allows the CPU to jump to another memory location and pushes the return address onto the stack. An example of this would be:
JSR $8005
This tells the CPU to jump to the memory address of $8005 to execute the next instruction there.

Those are just three of the 56 opcodes of the 6502; the rest can be found in my GitHub repo.

INITIAL STATES AND RESET

When we first power on the CPU, I am setting all values to a known state. This is not completely what a real 6502 start up would look like; however, for our purposes, this works just fine.

void power_up(cpu_6502 *cpu) {
    cpu->A = 0;
    cpu->X = 0;
    cpu->Y = 0;
    cpu->pc = 0;
    cpu->S = 0xFD;
    cpu->P = 0x24;
}

The reset function is similar to the power up, but sets the pc to the desired location to start reading memory at.

void reset(cpu_6502 *cpu, uint8_t *memory) {
    cpu->A = 0;
    cpu->X = 0;
    cpu->Y = 0;
    cpu->pc = memory[0xFFFC] | (memory[0xFFFD] << 8);
    cpu->S = 0xFD;
    cpu->P = 0x24;
}

STEPPING THROUGH MEMORY

Now we can go about discussing how the CPU steps through memory. The CPU will loop through the memory, increasing the program counter as directed by each instruction it decodes. This means for our program, the CPU will read a piece of memory (the opcode) and then, knowing that opcode, will determine the next step. This is achieved in the program by using our step function, whose signature can be found below:
void step(cpu_6502 *cpu, uint8_t *memory);
It will take a pointer to the CPU so we can update the registers and the memory array.
The function first grabs the opcode like so:
uint8_t opcode = mem_read(memory,cpu->pc++);
Then we have a switch statement that goes through all of the possible opcodes we could have read. If the opcode seems to be something we do not recognize, then for now, we print in the terminal that the opcode is unknown.
default:
printf("unknown opcode 0x%X\n",opcode);
break;

This is really the heart of our CPU, as we need to be able to step through memory in order to update the registers and flags to actually run programs.

TESTING

For this initial version of the CPU, I am simply testing to see that we can accurately decode our opcodes and step through the memory so we have a solid base for our NES emulator. For this, I am not writing anything to read a file. I will just test by manually setting some memory in our array. The test I am using is below in a main.c from my repo.

int main(){
    uint8_t memory[65536] = {0};


    cpu_6502 cpu;
    power_up(&cpu);


    memory[0x0000] = 0xA9; // LDA #$05
    memory[0x0001] = 0x05;


    memory[0x0002] = 0xAA; // TAX


    memory[0x0003] = 0xE8; // INX


    memory[0x0004] = 0xA0; // LDY #$10
    memory[0x0005] = 0x10;


    memory[0x0006] = 0xC8; // INY


    for (int i = 0; i < 5; i++) {
        step(&cpu, memory);


        printf("A=%02X X=%02X Y=%02X PC=%04X SP=%02X\n", cpu.A, cpu.X, cpu.Y, cpu.pc, cpu.S);
    }


    return 0;
}

This code manually writes some commands into memory, then runs our step function 6 times over the memory and prints the value of each register. You may note that there aren’t 6 commands we are manually writing to memory. This is correct and a good way to see our unknown opcode output in action. Below is the output of our test program

A=05 X=00 Y=00 PC=0002 SP=FD
A=05 X=05 Y=00 PC=0003 SP=FD
A=05 X=06 Y=00 PC=0004 SP=FD
A=05 X=06 Y=10 PC=0006 SP=FD
A=05 X=06 Y=11 PC=0007 SP=FD

First, we call LDA with the value 0x05, which loads 5 into the A register. We then call TAX, which loads A into the X register. We then call INX, which increments X by 1, so X is now 6. We then call LDY with the value 10, which loads 10 into the Y register. And then call INY, which increments Y by 1.

WHAT’S NEXT

Now that we have a working emulator for the 6502 CPU, we can go full steam ahead and look at how the NES actually uses its 64kb of memory. Once we have that, we will be able to read NES ROMs into our program memory and have full programs running on our CPU from files on our computer. After that, we can get into the really exciting stuff and work on the PPU and output the graphics onto our screens.