typestar

Two's complement in Assembly

neg flips sign; signed jumps read it correctly.

; Two's complement: neg flips sign, signed jumps read it right.
        global _start

        section .text
_start:
        mov rax, 25
        neg rax                 ; -25

        cmp rax, 0
        jl .below               ; signed less-than sees the sign
        mov rdi, 0
        jmp .exit
.below:
        neg rax                 ; back to 25
        lea rdi, [rax + rax]    ; 50
.exit:
        mov rax, 60             ; exit code 50
        syscall

How it works

  1. neg rax computes 0 minus the value.
  2. jl is the *signed* less-than jump.
  3. Exit codes are unsigned — return the positive 50.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
360
Tokens
46
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 50 seconds.

Type this snippet

Step 3 of 3 in Arithmetic, step 6 of 31 in Language basics.

← Previous Next →