5.29 · exercise

Machine code detective

A 32-bit instruction word arrives on standard input in hex. If it is an add or subtract between registers (the shifted-register format), take it apart and print the instruction it encodes. With the stdin box as given the program prints:

sf=1 op=0 S=0 shift=0 imm6=0
Rm=2 Rn=1 Rd=0
add x0, x1, x2

The format, from bit 31 down:

bits31302928-2423-222120-1615-109-54-0
fieldsfopS01011shift0Rmimm6RnRd
  • sf is 1 for x registers and 0 for w registers
  • op is 0 for add and 1 for sub; S is 1 when the instruction sets the flags, so op * 2 + S indexes the mnems table (add, adds, sub, subs)
  • shift picks lsl, lsr or asr (3 is not allowed), and imm6 is how far Rm is shifted first; leave the shift off the printed line when imm6 is 0
  • in this format register number 31 is the zero register, printed xzr or wzr

ubfx wD, wN, lsb, width copies width bits starting at bit lsb into the bottom of wD, which is exactly what each field needs. A word whose bits 28 to 24 are not 01011, whose bit 21 is 1, or whose shift field is 3 is some other instruction: print not an add or sub (shifted register) and return 1.

What is checked

  • all three lines for the word in the stdin box, and for more words you cannot see
  • the exit status (0, or 1 for a word of another format)
  • the fields come out with ubfx

specification

stdin8b020020
stdoutprints the right output
exitexits with the right code
sourceuses ubfx
hiddenright output and exit code on 7 more inputs you do not see

We run your program on the input above and on the hidden ones, and compare what it does. Nothing is matched against a stored solution.

loading editor...

regfile

N clearZ clearC clearV clear

x0–x30 are the integer registers.

X0arg00x0000000000000000
X1arg10x0000000000000000
X2arg20x0000000000000000
X3arg30x0000000000000000
X4arg40x0000000000000000
X5arg50x0000000000000000
X6arg60x0000000000000000
X7arg70x0000000000000000
X8ind0x0000000000000000
X90x0000000000000000
X100x0000000000000000
X110x0000000000000000
X120x0000000000000000
X130x0000000000000000
X140x0000000000000000
X150x0000000000000000
X16ip00x0000000000000000
X17ip10x0000000000000000
X18pr0x0000000000000000
X190x0000000000000000
X200x0000000000000000
X210x0000000000000000
X220x0000000000000000
X230x0000000000000000
X240x0000000000000000
X250x0000000000000000
X260x0000000000000000
X270x0000000000000000
X280x0000000000000000
X29fp0x0000000000000000
X30lr0x0000000000000000
SP0x0000000080000000
PC0x0000000000400000
console

Output prints here as your program runs.

Press step or run under the editor, or feed stdin from the box below.

not assembled

Open in playground