I'm new in the assembly universe and I can't find a simple way to write a number value in console with RISC-V64. I want to do something like that :
.data
x: .word 10
y: .word 2
.text
.global _start
_start:
li a0, 1
lw s0, x
lw s1, y
add a1, s0, s1
li a2, 2
li a7, 64
ecall
But I have a segmentation fault. Thanks
If you want any information about my problem, ask me !
The same program can write string without problem...
You're using the Write
system call, which writes bytes to a file, possibly stdout
, but could be any open file.
Its signature is Write ( int fileHandle, char *byteBuffer, int byteCount );
.
You have not provided the proper byte pointer for byteBuffer
parameter, instead you have provided a simple integer that is not a pointer, so when it interprets the buffer
parameter as a pointer as it is expecting, it crashes. This is a classic type mismatch, that a high level language would have prevented, but type mismatches are among many errors that assembly language is willing to let you make without build-time complaint.
In order to print bytes using Write
, you will need to provide a memory address (pointer) to the bytes you want to write. However, to start from a number to print, you will also need to convert the integer (result of the addition) from numeric form into a byte string in memory, then pass the address of that byte string and its length to Write
.
Most computer systems have a way to write ascii/unicode bytes, so to print a number using these facilities, convert the number to a byte string of ascii characters that represents the number in some number base like decimal, then print that byte string.
If using RARS, and you want to simply print an integer to the console in decimal, there is a different ecall
, named PrintInt
, and it will print the integer you place into a0
. It is ecall
number is 1 (goes into a7
). This is kind of a simple and easy way to print integers to the console (and even though it internally converts the number to a byte string for console output, there's no way to use this one to make a byte string for other purposes).
There's no options with ecall
1 (printInt) to print in different number base or to print leading zeros, or to print unsigned.
Were you to want any of that you'd be looking back at Write
and supplying the byte string of characters to print with some additional programming often referred to as itoa
(i.e. integer to ascii).