.global btohex

.section .rodata
hexchars:
  .ascii "0123456789ABCDEF"

.text

# Convert byte to ASCII hex
#    arguments:
#       a0: value to format
#   temporaries used:
#       t0, t1
#    return:
#       a0: value in ASCII hex
btohex:
  andi t0, a0, 0xF      # Mask off lower nybble
  la   a1, hexchars     # load address of hexchars
  add  a2, a1, t0       # offset to nybble
  lbu  t0, 0(a2)        # load hex char at offset
  srli t1, a0, 4        # shift upper nybble down
  andi t1, t1, 0xF      # mask off upper nybble
  add  a2, a1, t1       # offset to nybble
  lbu  t1, 0(a2)        # load hex char at offset
  mv a0, t1             # copy upper char to a0
  slli a0, a0, 8        # shuft upper char up
  or   a0, a0, t0       # OR the lower char into a0
  ret