; ARM assembly tutorial for Asmonite, example 15: 8 and 16 bit values (Raspberry Pi Pico 2, Arm Cortex-M33).
; Adapted from the ARM-ASM-Tutorial by Niklas Guertler (sections "8/16 bit arithmetic", "Alignment",
; "Offset addressing"); see LICENSE.txt.
;
; The registers are always 32 bit. A byte or a halfword is loaded into the low bits: "ldrb"/"ldrh" fill
; the rest with zeros, "ldrsb"/"ldrsh" with copies of the top bit (the sign). "uxtb" and "sxth" do the same
; with a register. "strb"/"strh" store the low 8 or 16 bits. Arithmetic is done in 32 bit; the result is
; cut when it is stored. Step with F7 and look at r0 .. r5 and at the memory from "values".
.target pico2
.arch thumb
.imagebase 0x20000000

_start:
    adr  r6, values
    ldrb  r0, [r6]              ; 0xf0: 240
    ldrsb r1, [r6]              ; 0xf0 as a signed byte: -16 (0xfffffff0)
    ldrh  r2, [r6, #2]          ; 0x8001: 32769
    ldrsh r3, [r6, #2]          ; -32767 (0xffff8001)
    adds  r4, r0, #0x20         ; 240 + 32 = 272 = 0x110: the register keeps 9 bits
    strb  r4, [r6, #4]          ; the byte gets 0x10: the top bit is lost
    uxtb  r5, r4                ; 0x10, the same cut in a register
    sxth  r5, r2                ; the halfword in r2 with its sign: -32767
    strh  r5, [r6, #6]          ; 0x8001 again
    b     $

    align 4
values:
    db 0xf0, 0                  ; offset 0: a byte, then one more to keep the halfword aligned
    dw 0x8001                   ; offset 2: a halfword (at an even address)
    db 0, 0                     ; offset 4: strb writes here
    dw 0                        ; offset 6: strh writes here
