blob: 896186888716424f13ecf0dc174a416cffeb7bd6 [file] [log] [blame]
Jens Axboe1ec3d692010-09-16 09:35:34 +02001#include <stdlib.h>
2#include <stdio.h>
3#include <string.h>
4
Jens Axboe10aa1362014-04-01 21:10:36 -06005#include "../fio.h"
6
Jens Axboeb7e147d2014-04-14 10:21:11 -06007#define ARRAY_LENGTH(arr) sizeof(arr) / sizeof((arr)[0])
8
Jens Axboe1ec3d692010-09-16 09:35:34 +02009/*
10 * Cheesy number->string conversion, complete with carry rounding error.
11 */
Steven Noonan73798eb2013-04-05 16:57:38 -070012char *num2str(unsigned long num, int maxlen, int base, int pow2, int unit_base)
Jens Axboe1ec3d692010-09-16 09:35:34 +020013{
Steven Noonan73798eb2013-04-05 16:57:38 -070014 const char *postfix[] = { "", "K", "M", "G", "P", "E" };
15 const char *byte_postfix[] = { "", "B", "bit" };
16 const unsigned int thousand[] = { 1000, 1024 };
Jens Axboe1ec3d692010-09-16 09:35:34 +020017 unsigned int modulo, decimals;
Steven Noonan73798eb2013-04-05 16:57:38 -070018 int byte_post_index = 0, post_index, carry = 0;
Jens Axboe05463812010-09-16 14:56:23 +020019 char tmp[32];
Jens Axboe1ec3d692010-09-16 09:35:34 +020020 char *buf;
21
22 buf = malloc(128);
23
24 for (post_index = 0; base > 1; post_index++)
25 base /= thousand[!!pow2];
26
Steven Noonan73798eb2013-04-05 16:57:38 -070027 switch (unit_base) {
28 case 1:
29 byte_post_index = 2;
30 num *= 8;
31 break;
32 case 8:
33 byte_post_index = 1;
34 break;
35 }
36
Jens Axboe1ec3d692010-09-16 09:35:34 +020037 modulo = -1U;
38 while (post_index < sizeof(postfix)) {
39 sprintf(tmp, "%lu", num);
40 if (strlen(tmp) <= maxlen)
41 break;
42
43 modulo = num % thousand[!!pow2];
44 num /= thousand[!!pow2];
Jens Axboe05463812010-09-16 14:56:23 +020045 carry = modulo >= thousand[!!pow2] / 2;
Jens Axboe1ec3d692010-09-16 09:35:34 +020046 post_index++;
47 }
48
49 if (modulo == -1U) {
50done:
Jens Axboeb7e147d2014-04-14 10:21:11 -060051 if (post_index >= ARRAY_LENGTH(postfix))
52 post_index = 0;
53
Steven Noonan73798eb2013-04-05 16:57:38 -070054 sprintf(buf, "%lu%s%s", num, postfix[post_index],
55 byte_postfix[byte_post_index]);
Jens Axboe1ec3d692010-09-16 09:35:34 +020056 return buf;
57 }
58
59 sprintf(tmp, "%lu", num);
60 decimals = maxlen - strlen(tmp);
Jens Axboe05463812010-09-16 14:56:23 +020061 if (decimals <= 1) {
62 if (carry)
63 num++;
Jens Axboe1ec3d692010-09-16 09:35:34 +020064 goto done;
Jens Axboe05463812010-09-16 14:56:23 +020065 }
Jens Axboe1ec3d692010-09-16 09:35:34 +020066
Jens Axboe05463812010-09-16 14:56:23 +020067 do {
68 sprintf(tmp, "%u", modulo);
69 if (strlen(tmp) <= decimals - 1)
70 break;
71
72 modulo = (modulo + 9) / 10;
73 } while (1);
74
Steven Noonan73798eb2013-04-05 16:57:38 -070075 sprintf(buf, "%lu.%u%s%s", num, modulo, postfix[post_index],
76 byte_postfix[byte_post_index]);
Jens Axboe1ec3d692010-09-16 09:35:34 +020077 return buf;
78}