{
  "id": "machine-code",
  "title": "Machine Code",
  "lang": "en",
  "source_lang": "en",
  "summary": "Machine code is the architecture-specific encoding of instructions that a processor executes to perform computation and control hardware.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Machine language",
    "Native machine code"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/machine-code/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/machine-code/",
      "json": "https://aiwiki.page/zh/machine-code.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Machine code is the encoded form of instructions defined by a processor’s instruction set architecture (ISA). These instructions direct a central processing unit or another programmable processor to perform operations such as arithmetic, memory access, comparison, and control transfer. Machine code is normally represented as sequences of binary digits, grouped into instruction words or bytes; hexadecimal notation provides a compact way for people to inspect those sequences.\n\nMachine code forms the principal interface between executable software and processor hardware. Programs written in higher-level programming languages generally reach a processor through compilation, interpretation implemented in native code, or translation during execution. The meaning of a particular instruction depends on the architecture and execution mode, while its performance also depends on the processor implementation. Understanding machine code therefore requires distinguishing instruction encodings from their semantics, executable files from the instructions they contain, and architectural behavior from the internal mechanisms used to implement it."
    },
    {
      "heading": "Instructions, data, and architectural meaning",
      "text": "A machine instruction is an encoded request to carry out an operation specified by an ISA. Its encoding commonly identifies an operation and one or more operands, although some operands can be implicit. An addition instruction might name two registers and a destination register; another architecture might implicitly use an accumulator. A return instruction can obtain its destination from a register or from memory rather than explicitly encoding the destination address. The instruction’s meaning includes not only its principal result but also effects on condition flags, exceptions, and other architectural state.\n\nThe bits that encode instructions are not inherently different from bits that encode numbers, text, or addresses. In a von Neumann architecture, instructions and data occupy a shared memory system, although modern processors commonly maintain separate instruction and data caches. A Harvard architecture separates instruction and data storage or access paths more fundamentally. In either case, the processor’s instruction-fetch mechanism and execution context determine which stored patterns are treated as instructions. A sequence of bytes in a file does not become executable merely because it happens to match a valid encoding.\n\nMachine code is distinct from assembly language, which expresses instructions using mnemonic names, register names, labels, and directives. For example, an assembly instruction such as add denotes an operation symbolically; an assembler converts the instruction into the corresponding encoding. The relationship is close but not always one-to-one. Assemblers may support pseudo-instructions that expand into several real instructions, select shorter encodings where possible, or accept several spellings for the same underlying operation. Assembly directives that reserve storage or define symbols may generate no executable instruction at all.\n\n“Machine code” also has a narrower meaning than “binary.” A binary file can contain images, compressed data, database records, or executable software. An executable commonly contains machine instructions alongside constants, relocation information, and metadata. Conversely, machine code need not reside in a conventional executable file: it can be stored in firmware, embedded in a boot image, or generated in memory during execution. It is also distinct from bytecode, whose immediate execution model is usually an abstract machine rather than a particular physical processor. Hardware can nevertheless be designed to execute an instruction set originally associated with a virtual machine."
    },
    {
      "heading": "Instruction encoding and binary representation",
      "text": "An instruction encoding assigns meaning to particular bit fields. An opcode identifies an operation or an operation family; other fields can specify registers, immediate constants, memory-addressing forms, or instruction modifiers. These fields need not occupy neat byte boundaries. A processor register number may require only a few bits, while a large immediate operand may occupy several bytes. Some encodings reserve patterns for future extensions, and some patterns are invalid in a particular execution mode even though they have a meaning elsewhere.\n\nFixed-width instruction sets allocate the same number of bits to each instruction within a particular encoding class. AArch64 instructions, for example, are 32 bits long. Variable-length instruction sets allow instructions of different sizes; x86 instructions can be from 1 to 15 bytes long. These choices affect decoding, code density, alignment, and extension mechanisms, but the distinction is not absolute across architecture families. RISC-V combines a base encoding with 32-bit instructions and optional extensions, including compressed 16-bit instructions. Arm’s Thumb encodings similarly illustrate that a processor family can support more than one instruction format.\n\nA concrete x86 example is the byte sequence B8 01 00 00 00. In ordinary 32-bit execution, and also in 64-bit mode without a relevant prefix, it encodes loading the immediate value 1 into the EAX register. The byte B8 identifies a move-immediate form and selects that register; the following four bytes encode the constant. By contrast, the AArch64 instruction word 0x91000400 encodes ADD X0, X0, #1. These examples perform different operations, but they illustrate how an instruction can combine an operation, register selection, and a constant in architecture-specific ways.\n\nEndianness determines the ordering of bytes within multibyte quantities. On a little-endian system, the least significant byte is stored at the lowest address. Thus the 32-bit quantity 0x91000400 appears in memory as 00 04 00 91 under little-endian storage. A printed instruction word and a byte-by-byte memory dump can therefore look different while representing the same encoding. Instruction byte ordering is an architectural rule and should not simply be assumed from how a system stores ordinary data.\n\nEncoding also governs the range of branches and immediate operands. If a signed branch displacement contains \\(k\\) bits and is measured in units of \\(a\\) bytes, its representable displacement is generally bounded by\n\n\\[-a2^{k-1}\\leq d\\leq a(2^{k-1}-1).\\]\n\nThe reference address used for that displacement is architecture-specific. When a destination is out of range, an assembler or linker may need a longer sequence or an intermediate branch target."
    },
    {
      "heading": "State changes, addressing, and control flow",
      "text": "The semantics of machine code can be described as transformations of architectural state. That state includes registers, memory, an instruction pointer or program counter, and control information such as privilege level and status flags. In a simplified mathematical model, an instruction \\(I\\) transforms a state \\(S\\) into another state:\n\n\\[S' = F_I(S).\\]\n\nReal specifications must also account for memory-access faults, interrupts, concurrency, and cases in which behavior is conditional or constrained rather than fully determined. This semantic view separates what an instruction must do from how a particular chip accomplishes it.\n\nInstructions obtain operands through addressing mechanisms. Register operands refer to storage directly accessible through the architecture’s register set. Immediate operands embed values in the instruction stream. Memory operands identify locations through addresses computed from registers, offsets, or combinations of both. Some architectures permit arithmetic instructions to access memory directly; load-store architectures normally require explicit load and store instructions to move values between memory and registers. Reduced instruction set computing is historically associated with this latter organization, although modern instruction sets contain many specialized variations.\n\nControl-flow instructions determine which instruction executes next. A direct branch encodes its destination or a displacement to it; an indirect branch obtains the destination from a register or memory. Conditional branches test a condition derived from flags, register comparisons, or another architectural mechanism. Function calls and returns are instruction-level mechanisms on which language implementations build procedure execution, but their precise realization varies. A call may push a return address onto a memory stack, place it in a link register, or participate in a more elaborate convention.\n\nMachine arithmetic is also more specific than arithmetic over unrestricted integers. An unsigned \\(n\\)-bit addition commonly produces a result equivalent to\n\n\\[r=(a+b)\\bmod 2^n,\\]\n\nwith any carry recorded separately if the architecture provides a carry flag. Signed interpretation, overflow reporting, saturation, and trapping behavior depend on the instruction. Floating-point instructions introduce additional rules for rounding, exceptional values, and supported formats. A compiler must map the source language’s rules onto these operations; the two levels do not necessarily assign the same meaning to every possible calculation.\n\nOrdinary application code executes within restrictions imposed by the operating system and processor. Privileged instructions can change address-translation settings, interrupt control, or other protected state and generally cannot be used freely by applications. A system call uses an architecture-defined transition mechanism to request operating-system services. Exceptions and interrupts likewise transfer control according to architectural rules, rather than behaving like ordinary calls between application functions."
    },
    {
      "heading": "How processors execute machine code",
      "text": "A simplified processor repeatedly fetches an instruction, decodes it, obtains operands, performs the operation, and makes its result part of architectural state. Actual implementations overlap and subdivide these activities. Instruction fetch may obtain many bytes or several instruction words at once. Decoding recognizes instruction boundaries and interprets fields. Execution units then carry out arithmetic, address generation, comparisons, and other operations. Even a processor that presents a straightforward sequential instruction set can contain a complex internal execution system.\n\nMany contemporary processors translate architectural instructions into internal operations, often called micro-operations. An instruction with several memory and arithmetic effects may become multiple internal operations, while some implementations can combine certain adjacent instructions for internal processing. Microcode is another implementation technique: control sequences stored inside the processor direct the execution of particular instructions or exceptional cases. Microcode is not the application’s machine code, and an instruction set does not require one unique microcode implementation. Some instructions are handled primarily by dedicated logic, while others use sequenced control.\n\nPipelining overlaps different stages of different instructions. Superscalar processors can issue more than one operation in a cycle when resources and dependencies allow. Out-of-order execution permits later operations to proceed before earlier ones have completed, provided architectural requirements are preserved. Register renaming removes false dependencies caused by reusing the same architectural register names. These mechanisms mean that the physical order of internal work can differ from the order in which machine instructions appear in memory.\n\nBranch prediction allows fetching and executing along a likely control-flow path before the relevant condition has been resolved. If the prediction is wrong, results from the incorrect path are discarded architecturally, and execution resumes on the correct path. Many out-of-order processors use an in-order retirement mechanism so that completed instructions become architecturally visible in the appropriate sequence. However, speculative activity can affect caches and other internal structures even when its register results are discarded, an important distinction in both performance analysis and security.\n\nMemory behavior adds another layer. A CPU cache can satisfy a load much faster than main memory, while address translation through virtual memory can introduce additional checks and delays. Stores may remain buffered after an instruction has progressed through execution. In systems with several processors or cores, the ISA’s memory model specifies which observations by other execution threads are permitted. Synchronization instructions and barriers constrain those observations. Consequently, machine code cannot always be understood as a simple sequence of immediately completed, globally visible memory accesses."
    },
    {
      "heading": "Compilation, linking, and loading",
      "text": "Machine code is commonly produced by a compiler from source code. A compiler analyzes the source program, constructs internal representations, performs transformations, and selects target instructions. Register allocation assigns values to the finite register set and inserts memory operations where necessary. Instruction scheduling arranges operations under dependency and target constraints. The compiler may emit assembly for a separate assembler or generate machine-code bytes directly; an assembly-language file is not an obligatory intermediate artifact.\n\nThe first output is often an object file, rather than a complete runnable program. An object file can contain instruction bytes, initialized data, symbols, relocation records, and debugging information. Its code may refer to functions or objects whose final locations are not yet known. A linker combines such files and libraries, resolves symbol references, and applies relocations. For a relative reference, the required value often depends on the relationship between the target symbol’s address and the location of the reference. Relocation records identify the calculation and the field that must be patched.\n\nThe resulting executable file packages code with information needed to establish a process. Common formats include ELF on many Unix-like systems, Portable Executable on Microsoft Windows, and Mach-O on Apple platforms. These formats describe regions or sections, permissions, entry information, and dependencies; their organization is not itself an instruction set. A loader maps appropriate regions into memory, arranges initial state, and transfers control to startup code. Dynamically linked programs also involve a runtime linker that locates shared libraries and resolves required references.\n\nThe application binary interface (ABI) supplies conventions beyond instruction semantics. It specifies matters such as argument passing, return values, register preservation, stack alignment, and data layout. Two functions can use valid instructions for the same processor yet fail to interoperate because they follow incompatible calling conventions. Similarly, an ISA-compatible executable is not automatically compatible with a different operating system’s executable format or system-call interface. ISA compatibility, ABI compatibility, and operating-system compatibility are related but distinct requirements.\n\nNot all code is generated before a program starts. Just-in-time compilation translates a program representation into machine code during execution, often using runtime information to specialize frequently executed paths. Modern JavaScript engines are a prominent example. Such systems manage executable memory, preserve mappings to higher-level program state, and may replace or discard generated code. They can also revert from optimized code when assumptions cease to hold. The resulting instructions are still machine code, despite being temporary and absent from the original executable file."
    },
    {
      "heading": "Architecture dependence, compatibility, and translation",
      "text": "Machine code is specific to an instruction set and often to a subset or extension of that set. An x86-64 program cannot normally run directly on an AArch64 processor because the same bit patterns do not identify the same operations. Even within one family, compatibility depends on details such as execution mode, available registers, supported extensions, privilege rules, and memory behavior. A binary containing an instruction introduced after a processor was designed may fault when that instruction is reached.\n\nBackward compatibility can preserve substantial bodies of software across processor generations. The x86 family, beginning with Intel’s 8086 in 1978, is a major example of an architecture evolving through extensions while retaining extensive earlier functionality. Compatibility is not unlimited: later operating environments may omit older execution modes or interfaces, and specific instructions can behave differently under privileged settings or virtualization. A claim that two processors support “x86” therefore conveys less than a precise account of mode, feature level, and platform requirements.\n\nA program can contain several implementations of a function and choose among them at runtime. For example, a library may include a baseline routine and alternatives using newer vector instructions. Feature detection selects an implementation that the current processor and operating system can support. Operating-system participation matters because some extensions require additional register state to be enabled and preserved across context switches. A distribution can also package separate binaries for different architectures rather than attempting to make one instruction stream universal.\n\nBinary translation converts machine code for one execution environment into code suitable for another. Static translation operates before execution, whereas dynamic translation converts blocks as they are encountered and may cache the results. Correct translation must preserve more than arithmetic: it may need to reproduce flags, exception behavior, atomic operations, and memory ordering. Address-space layout, self-modifying code, and interactions with the operating system complicate the task. Interpretation offers another approach, executing a software routine that models each guest instruction or operation.\n\nA virtual machine does not necessarily imply a different machine-code architecture. Hardware-assisted virtualization can allow much guest code to execute directly on the host processor while controlling privileged operations and memory mappings. Emulation, by contrast, can reproduce a different processor in software, although terminology sometimes overlaps in practical products. GPU instruction sets create another boundary: graphics processing unit programs may pass through intermediate representations before becoming device-specific machine code. A portable intermediate format is therefore not necessarily the native encoding executed by the final device."
    },
    {
      "heading": "Performance, code size, and optimization",
      "text": "Machine-code performance depends on both the instruction sequence and the hardware executing it. Counting instructions alone gives an incomplete picture. A useful accounting identity is\n\n\\[T=\\frac{N\\times \\mathrm{CPI}}{f},\\]\n\nwhere \\(T\\) is execution time, \\(N\\) is the number of executed instructions, \\(\\mathrm{CPI}\\) is average cycles per instruction, and \\(f\\) is clock frequency. The average CPI depends on dependencies, execution resources, memory delays, and branch behavior; it is not a fixed property of the instruction set. Changes in frequency during execution also require more careful measurement than this simplified expression suggests.\n\nLatency and throughput describe different constraints. Instruction latency measures the delay before a dependent operation can use a result. Throughput concerns the rate at which operations can be processed when sufficiently independent work is available. A chain of dependent additions may be limited by latency, while several independent arithmetic streams can use multiple execution resources. A shorter instruction sequence can therefore be slower than a longer one if it creates a more restrictive dependency chain or uses a heavily contended execution unit.\n\nCode size affects instruction fetching and cache behavior. Compact code can reduce instruction-cache misses and pressure on instruction-translation structures. Conversely, alignment and selective duplication can sometimes improve branch behavior or remove control overhead. Loop unrolling illustrates the trade-off: it reduces branch and loop-management work and can expose independent operations, but increases code size and register demand. Excessive unrolling may cause register spills or displace useful code from caches. The best result depends on the surrounding program and the target processor.\n\nCompilers exploit these interactions through instruction selection, vectorization, scheduling, and profile-guided optimization. Vector instructions operate on multiple data elements, but their usefulness depends on data layout, dependencies, and the cost of preparing operands. A nominally powerful instruction is not automatically faster than several simpler ones. Different processors implementing the same ISA can assign very different costs to particular operations, so compiler tuning distinguishes the instructions a target supports from the implementation for which the sequence is optimized.\n\nMachine code also influences parallel computing through atomic operations and memory synchronization. Atomic read-modify-write instructions support locks, counters, and other coordination mechanisms, but contention can dominate their cost. Memory barriers can prevent otherwise useful reordering, and independent variables on the same cache line can still interfere through coherence traffic. These effects connect instruction-level choices to memory hierarchy and system-level behavior. Reliable analysis consequently combines inspection of generated instructions with measurements of the actual workload rather than treating assembly listings as complete performance explanations."
    },
    {
      "heading": "Inspection, security, and correctness",
      "text": "A disassembler converts encoded instructions into a symbolic representation. This is useful for debugging compiler output, examining crashes, analyzing firmware, and studying software without its source. Disassembly does not generally recover the original source program. Variable names, comments, types, and higher-level structure may be absent, while optimization can merge, eliminate, or rearrange source-level constructs. Debugging information can restore some associations, but it is auxiliary data rather than an intrinsic part of the machine instructions.\n\nIdentifying instruction boundaries can itself be difficult. In a variable-length instruction set, beginning decoding at different byte offsets can produce different valid instruction sequences. Executable regions may contain embedded constants, jump tables, padding, or unreachable bytes. Indirect control transfers can make it hard to determine all possible destinations. Decompilers attempt to reconstruct higher-level operations and control structures, but their output is an interpretation of the binary’s behavior, not a guaranteed reproduction of the program from which it originated.\n\nMachine code lies at the center of several cybersecurity mechanisms. Memory permissions can distinguish readable, writable, and executable pages. Non-executable data pages help prevent injected data from being executed, while write-xor-execute policies restrict memory from being writable and executable simultaneously. These protections do not make every attack impossible. Code-reuse attacks can redirect control through instruction sequences already present in executable memory. Such attacks exploit errors in control or memory safety rather than requiring an entirely new instruction stream to be stored and executed.\n\nAn ISA’s correctness guarantees also differ from broader security properties. An instruction can have precisely defined architectural effects while its timing or cache behavior reveals information. Speculative execution and memory-system interactions demonstrate why architectural state is not the only observable aspect of computation. Constant-time implementations of cryptography seek to avoid secret-dependent control flow or memory access patterns, but generated machine code and target-specific behavior matter. Source code that appears regular can be transformed into a less suitable instruction sequence by optimization.\n\nFormal verification can reason about machine-code behavior using mathematical models of the ISA. Applications include verifying individual routines, checking compiler transformations, and establishing properties of operating-system components. The proof must specify its assumptions, including initial memory state, permitted inputs, concurrency, and hardware behavior. A proof over an architectural model does not automatically establish the absence of timing leakage, electrical fault effects, or implementation defects. Binary instrumentation and runtime checking offer complementary approaches, inserting monitoring operations or redirecting execution to detect selected classes of incorrect behavior."
    },
    {
      "heading": "Historical development and continuing uses",
      "text": "Machine code emerged with programmable electronic computers, but early machines did not all acquire programs in the same way. Some systems were configured through switches, cables, or externally supplied instruction media. The stored-program approach made instructions into values that could be held in electronic memory and fetched during computation. In June 1948, the Manchester Small-Scale Experimental Machine, commonly called the Manchester Baby, successfully ran a stored program. In 1949, EDSAC at Cambridge began performing practical stored-program calculations. Their instruction formats were specific to their hardware, not universal binary languages.\n\nEarly programmers often worked directly with numeric operation codes and addresses, using binary, octal, or decimal notation according to the machine and its tools. Symbolic assemblers reduced the burden of remembering operation codes and manually recalculating addresses. Higher-level languages then moved more program construction away from individual instructions. The first widely successful Fortran compiler, developed at IBM under John Backus and released in 1957, demonstrated that high-level numerical programming could produce efficient machine code. This changed how programs were written without removing machine instructions from execution.\n\nArchitecture families made machine-code compatibility a commercial and engineering objective. Announced in 1964, IBM System/360 offered a common architecture across machines with different performance characteristics. The distinction between a programmer-visible instruction set and its implementation became especially consequential: implementations could use different internal organizations while running compatible software. Later microprocessors brought architecture-specific machine code into inexpensive systems, including embedded controllers and personal computers. The growth of software libraries and operating systems made continuity of binary interfaces increasingly valuable.\n\nThe RISC projects of the late 1970s and 1980s revisited the relationship between instruction complexity, compiler design, and implementation efficiency. Their influence extended to commercial architectures with regular encodings, large register sets, and load-store operation. Meanwhile, established instruction sets evolved through pipelining, caching, internal instruction translation, and specialized extensions. The result was not a simple replacement of complex instruction sets by simple ones: both architectural traditions acquired sophisticated implementations and increasingly specialized operations for vector processing, cryptography, and other workloads.\n\nMachine code remains essential in domains where precise hardware interaction or resource constraints matter. Boot loaders establish an initial execution environment; firmware initializes and controls devices; device drivers coordinate operating-system requests with hardware interfaces. Embedded software may execute directly from nonvolatile storage with little or no conventional operating-system support. Runtime systems, compilers, debuggers, and performance tools all depend on detailed knowledge of instruction behavior. Even when most application development takes place far above this level, the machine-code boundary determines which operations the hardware exposes and how software can invoke them."
    }
  ],
  "links": [
    "central-processing-unit",
    "programming-language",
    "bit",
    "von-neumann-architecture",
    "assembly-language",
    "metadata",
    "byte",
    "operating-system",
    "system-call",
    "cpu-cache",
    "virtual-memory",
    "compiler",
    "source-code",
    "executable-file",
    "microsoft-windows",
    "javascript",
    "virtual-machine",
    "virtualization",
    "graphics-processing-unit",
    "parallel-computing",
    "memory-hierarchy",
    "cybersecurity",
    "cryptography",
    "formal-verification",
    "fortran",
    "ibm",
    "personal-computer",
    "device-driver"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}