I am new to assembly, but could anyone teach me how to read 64 bit from console in 32 bit RISC-V?
.eqv SYS_EXITO, 10
.eqv CON_PRTSTR, 4
.eqv CON_PRTINT, 1
.eqv CON_RDINT, 5
.eqv BUFSIZE, 100
.data
prompt:
.asciz "Read 64 bit integer:"
result:
.asciz "Output:"
buf:
.space BUFSIZE
.text
main:
la a0, prompt
li a7, CON_PRTSTR
ecall
la a0, buf
li a1, BUFSIZE
li a7, CON_RDINT
ecall
Then we I input 4294967295, the following error occured.
Error in /private/var/folders/bf/t4py6npj0v38grsvrgvq1dx00000gn/T/hsperfdata_sotarosuzuki/riscv1.asm line 24: Runtime exception at 0x00400020: invalid integer input (syscall 5)
So, should I read the integers as string and convert it to integer? I have searched for this solution, but I cannot find it.
Yeah, if you can't use the toy system calls, read a string and do
total = total*10 + digit
on it, wheredigit = c-'0'
. You'll need to do extended-precision multiply, so it's probably easier to do extended-precision shifts like(total << 3) + (total << 1)
.Check compiler output on Godbolt. For example, GCC using shifts, clang using
mul
/mulhu
(high unsigned) for thelo * lo
32x32=>64-bit partial product, and amul
for the high half cross product (hi * lo
). It's fewer instructions, but depends on a RISC-V CPU with a fast multiplier to be faster than shift/or.(RISC-V extended-precision addition is inconvenient since it doesn't have a carry flag, you need to emulate carry-out as
unsigned sum = a+b;
carry = sum<a;
)Clang's output is shorter, so I'll show it. It of course follows the standard calling convention, taking the pointer in
a0
, and returning a 64-bit integer in a pair of registers,a1:a0
:If you want to go with GCC's shift/or strategy, it should be straightforward to see how that slots in to the same logic clang is using. You can look at compiler output for a function like
return u64 << 3
to see which instructions are part of that.And BTW, I wrote the C with compiling to decent asm in mind, making it easy for the compiler to transform it into a
do{}while
loop with the condition at the bottom. I based it on the x86 asm in my answer on NASM Assembly convert input to integer?