-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnum_format.c
66 lines (53 loc) · 1.5 KB
/
num_format.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "num_format.h"
#include <xdc/runtime/Assert.h>
#include <string.h>
/* Large enough to hold string repr of a 64-bit number in base 2 */
#define MAX_NUM_LENGTH 64
static Char numberBuf[MAX_NUM_LENGTH + 1]; /* one for null byte */
static Char *numberBufEnd = numberBuf + MAX_NUM_LENGTH;
static const Char digtohex[] = "0123456789abcdef";
/* Adapted from System_fomatNum to handle 64-bit
* ======== System_formatNum ========
* Format singed or unsigned 64-bit number in specified base,
* and return a pointer to the output string in a private buffer.
*
* Note: base is negative if n is signed else n unsigned!
*
* un - The unsigned number to be formated
* base - The base to format the number into. TODO - signed?
*/
Char* NumFormat_format(UInt64 un, Int zpad, Int base)
{
Int i = 0;
Char sign = 0;
UInt64 n;
n = un;
Char *ptr = numberBufEnd;
*ptr = '\0';
if (base < 0) {
/* handle signed long case */
base = -base;
if ((Int64)n < 0) {
n = -(Int64)n;
/* account for sign '-': ok since zpad is signed */
--zpad;
sign = '-';
}
}
/* compute digits in number from right to left */
do {
*(--ptr) = digtohex[(Int) (n % base)];
n = n / base;
++i;
} while (n);
/* pad with leading 0s on left */
while (i < zpad) {
*(--ptr) = '0';
++i;
}
/* add sign indicator */
if (sign) {
*(--ptr) = sign;
}
return (ptr);
}