● fixed X

乗算

乗算は fixed_mul で行います。
例1.数値文字列を FIXEDVAL値に変換

#include <memory.h>
#include <ctype.h>
#include "fixedX.h"

#define BIT             64
#define SIZE            (BIT / 8)

/* 10進数の文字列を FIXEDVAL値に変換する */
int         aton(char *psrc,PFIXEDVAL pval)
{
    static FIXEDVAL     ten[SIZE] = {10},chr[SIZE] = {0};
    FIXEDVAL            result[SIZE * 2]; /* fixed_mul の結果を格納する
                                             SIZE * 2 の大きさが必要 */

    memset(pval,0,SIZE); /* ゼロクリアしておく */

    while(*psrc){
        if (!isdigit(*psrc)) return 0;

        fixed_mul(pval,ten,result,SIZE); /* val * 10 */
        chr[0] = (FIXEDVAL )(*psrc++ - '0');
        fixed_add(result,chr,SIZE);      /* (val * 10) + (*psrc - '0') */
        memcpy(pval,result,SIZE);
    }

    return 1;
}

#include <stdio.h>
#include <stdlib.h>

void        main(void )
{
    FIXEDVAL        a[SIZE];
    char            buf[20+1];

    aton("21474836475",a);

    fixed_num2str10(a,SIZE,buf);
    printf("%s\n",buf);
}
乗算は、積を格納する領域を別に指定します。加減算のように、引数 a に上書きされません。
    fixed_mul(a,b,c,width );   →   c = a * b
結果格納先の数値幅は width の2倍以上必要です。使用前にゼロクリアしておく必要はありません。

なお、結果領域と被乗数に、同じ領域を指定する事はできません。結果領域と乗数も同様です。
○
    c ← a * a
    c ← b * b

×
    a ← a * b
    b ← a * b


fixed X では、加減乗除全てに FIXEDVAL値と 32bit値の計算を行う関数が用意されています。上記の例のように、乗数が定数である、といった場合には便利です。
次の例は、FIXEDVAL値 × 32bit値を行う fixed_mul32 と FIXEDVAL値 + 32bit値を行う fixed_add32 を使って、関数aton を書き換えたものです。
例2.

/* 10進数の文字列を FIXEDVAL値に変換する */
int         aton(char *psrc,PFIXEDVAL pval)
{
    FIXEDVAL            result[SIZE * 2];

    memset(pval,0,SIZE); /* ゼロクリアしておく */

    while(*psrc){
        if (!isdigit(*psrc)) return 0;

        fixed_mul32(pval,10,result,SIZE);       /* val * 10 */
        fixed_add32(result,*psrc++ - '0',SIZE); /* (val * 10) + (*psrc - '0') */
        memcpy(pval,result,SIZE);
    }

    return 1;
}