114 lines
2.5 KiB
C
114 lines
2.5 KiB
C
|
|
#ifndef __CELOXICA_PRINT_BASE_H__
|
|
#define __CELOXICA_PRINT_BASE_H__
|
|
|
|
#ifndef __STDC_FORMAT_MACROS
|
|
#define __STDC_FORMAT_MACROS
|
|
#endif // __STDC_FORMAT_MACROS
|
|
|
|
#include <stdio.h>
|
|
#include <assert.h>
|
|
#include <inttypes.h>
|
|
|
|
static void PrintBaseUInt64 (FILE *f, uint64_t Value, int CurrentOrder, int BeforeDecPoint, int AfterDecPoint, char *Unit) __attribute__ ((unused));
|
|
|
|
static void PrintBaseUInt64 (FILE *f, uint64_t Value, int CurrentOrder, int BeforeDecPoint, int AfterDecPoint, char *Unit)
|
|
{
|
|
const char *Units[] = {"y", "z", "a", "f", "p", "n", "u", "m",
|
|
"",
|
|
"K", "M", "G", "T", "P", "E", "Z", "Y"};
|
|
const int Orders[] = {-24, -21, -18, -15, -12, -9, -6, -3,
|
|
0,
|
|
3, 6, 9, 12, 15, 18, 21, 24};
|
|
|
|
/*
|
|
* Align the order
|
|
*/
|
|
while (CurrentOrder % 3)
|
|
{
|
|
Value *= 10;
|
|
CurrentOrder--;
|
|
}
|
|
|
|
/*
|
|
* Find the closest base unit
|
|
*/
|
|
uint64_t Div = 1;
|
|
int OrderShift = 0;
|
|
uint64_t MaxOutput = 1;
|
|
int x;
|
|
for (x=0; x<BeforeDecPoint; x++)
|
|
{
|
|
MaxOutput *= 10;
|
|
}
|
|
while ((Value / Div) >= MaxOutput)
|
|
{
|
|
Div *= 1000;
|
|
OrderShift += 3;
|
|
}
|
|
|
|
/*
|
|
* Print before decimal point
|
|
*/
|
|
fprintf (f, "%*" PRIu64, BeforeDecPoint, Value / Div);
|
|
|
|
/*
|
|
* Print after decimal point
|
|
*/
|
|
if (AfterDecPoint)
|
|
{
|
|
int i;
|
|
uint64_t Factor = 1;
|
|
for (i=0; i<AfterDecPoint; i++)
|
|
{
|
|
Factor *= 10;
|
|
}
|
|
uint64_t R = Value % Div;
|
|
int OS = OrderShift;
|
|
while (OS != AfterDecPoint)
|
|
{
|
|
if (OS < AfterDecPoint)
|
|
{
|
|
OS++;
|
|
R *= 10;
|
|
}
|
|
else
|
|
{
|
|
OS--;
|
|
R /= 10;
|
|
}
|
|
}
|
|
|
|
//char Temp[256];
|
|
//sprintf (Temp, ".%%0%dlu", AfterDecPoint);
|
|
//fprintf (f, Temp, R);
|
|
fprintf (f, ".%0*" PRIu64, AfterDecPoint, R);
|
|
}
|
|
|
|
/*
|
|
* Print order and user unit
|
|
*/
|
|
unsigned int i;
|
|
for (i=0; i<(sizeof(Orders)/sizeof(int)); i++)
|
|
{
|
|
if ((CurrentOrder + OrderShift) == Orders[i])
|
|
{
|
|
fprintf (f, "%s%s%s", Units[i], Unit, Orders[i]==0 ? " ":"");
|
|
return;
|
|
}
|
|
}
|
|
fprintf (f, "??");
|
|
assert (0);
|
|
}
|
|
|
|
#if 0
|
|
int main ()
|
|
{
|
|
UnitPrintUINT64 (stdout, 1100000, 0, 1, "s");
|
|
printf (".\n");
|
|
return 0;
|
|
}
|
|
#endif
|
|
|
|
#endif
|