Reputation: 646
I'm writing assembly on a 32-bit PowerPC system (specifically, a GameCube). I have a 64-bit integer that I need to convert to a floating-point number. How can I do this? Examples I can find online all involve the use of fcfid
instruction, but this is only available on 64-bit systems.
The code so far is:
CALL __OSGetSystemTime # -> u64 ticks in r3, r4
stw r3, SP_FLOAT_TMP(r1)
stw r4, (SP_FLOAT_TMP+4)(r1)
lfd f1, SP_FLOAT_TMP(r1)
fcfid f1 # u64 -> double
frsp f1 # double -> float
(CALL
is a macro for position-independent bl
)
The GNU Assembler gives an error:
Error building debugprint debugprint.s: Assembler messages:
debugprint.s:345: Error: unrecognized opcode: `fcfid'
Upvotes: 1
Views: 882
Reputation: 26185
I have not used PowerPC since the early 2000s, so I will present C code that outlines an algorithm that I think will be translatable into 32-bit PowerPC instructions. The basic idea is to split the 64-bit integer into two 32-bit halves comprising the most significant and least significant bits, respectively. Convert each half to a double
using the magic-number addition technique. Combine the two resulting doubles using a fused multiply-add (FMA) operation, scaling the high half by 232. This incurs just a single rounding.
Because this is a conversion of unsigned integers, the magic number we need here is 252. Construct the binary image of that number in memory, then place the 32-bit integer N into the least significant 32 bits. This creates the binary image of a double
with the value 252+N. Load that double
from memory, then subtract out 252, leaving N in the floating-point register. The result is exact.
I have annotated the ISO-C99 code with the PowerPC instructions I think one would use to code this in assembly language.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h> // for memcpy
#include <math.h> // for fma
/* re-interpret a 64-bit unsigned integer in two halves as a double */
double hilo_uint32_as_double (uint32_t hi, uint32_t lo)
{
double r;
uint64_t t = ((uint64_t)hi << 32) + (uint64_t)lo;
memcpy (&r, &t, sizeof r);
return r;
}
double uint64_to_double (uint64_t a)
{
const double two_to_32 = 0x1.0p32;
const double magic = hilo_uint32_as_double (0x43300000, 0); // 0x1.0p52
/* split 64-bit number into two 32-bit halves */
uint32_t hi = (uint32_t)(a >> 32); // stw
uint32_t lo = (uint32_t)(a & 0xffffffff); // stw
/* convert each 32-bit half into a double */
double lof = hilo_uint32_as_double (0x43300000, lo) - magic; // stw, lfd, fsub
double hif = hilo_uint32_as_double (0x43300000, hi) - magic; // stw, lfd, fsub
/* combine halves with a single rounding */
return fma (hif, two_to_32, lof); // fmadd
}
int main (void)
{
uint64_t a = 1234567890123456ULL;
printf ("%llu -> %23.16e\n", a, uint64_to_double (a));
return EXIT_SUCCESS;
}
Upvotes: 2