ARMv8 Assembly, How to cast integer value to float value, and how to print it?

1.5k Views Asked by At

When I try to cast an integer into a float and print it out, the value stored in that register turns to 0.000000.

outI: .string "%d\n"
outF: .string "%f\n"

      mov        x20,      160
            
      mov        x1,       x20
      ldr        x0,       =outI
      bl         printf
            
      scvtf      s20,      x20      //cast x20 to float
            
      fmov       s0,       s20
      ldr        x0,       =outF
      bl         printf

When I try to run above code, The value printed out is:

160
0.000000

Did I give wrong print instruction?

1

There are 1 best solutions below

0
On

The %f format specifier for printf expects an argument of type double, but by passing a single-precision floating point value in s0, you are effectively passing float instead.

(In fact, variadic functions such as printf can never take an argument of type float. If you try to pass a float argument to printf from C code in C, it will be implicitly promoted to double, but of course assembly won't do that for you.)

So you need instead to get a double-precision floating point value in d0. If you've already got a single-precision float in s20, then the simplest approach is to replace your fmov s0, s20 with fcvt d0, s20 to convert it to double precision.