typestar

Shift and mask in Assembly

Pull packed fields out of a value.

; Shift and mask pulls fields out of packed values.
        global _start

        section .text
_start:
        mov rax, 0xA5C3         ; two packed bytes

        mov rbx, rax
        and rbx, 0xFF           ; low byte: 0xC3 = 195

        mov rcx, rax
        shr rcx, 8              ; high byte down
        and rcx, 0xFF           ; 0xA5 = 165

        sub rbx, rcx            ; 195 - 165 = 30
        mov rdi, rbx
        mov rax, 60             ; exit code 30
        syscall

How it works

  1. and rbx, 0xFF keeps the low byte.
  2. shr brings the high byte down before masking.
  3. 0xC3 minus 0xA5 = 30 exits.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
386
Tokens
49
Three-star pace
55 tpm

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

Type this snippet

Step 2 of 4 in Bits & flags, step 16 of 31 in Language basics.

← Previous Next →