summaryrefslogtreecommitdiff
path: root/src/kernel/util.c
blob: c7a50351df46f8e5e40ef7ab7f762659a595157a (plain) (blame)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdint.h>
#include "panic.h"
#include <stdbool.h>

void memcpy(void *to, void *from, uint32_t n) {
  uint32_t *tp = to, *fp = from;
  while (n >= 4) {
    *(tp++) = *(fp++);
    n -= 4;
  }
  uint8_t *tpp = (uint8_t *)tp, *fpp = (uint8_t *)fp;
  while (n--)
    *(tpp++) = *(fpp++);
}

void u32_dec(uint32_t n, uint8_t *b) {
  if (!n) {
    *(uint16_t *)b = '0';
    return;
  }
  bool zero = false;
  for (uint32_t m = 1000000000; m; m /= 10) {
    uint8_t d = (n / m) % 10;
    if (zero)
      *(b++) = d + '0';
    else if (d) {
      zero = true;
      *(b++) = d + '0';
    }
  }
  *b = 0;
}

void u16_dec(uint16_t n, uint8_t *b) {
  if (!n) {
    *(uint16_t *)b = '0';
    return;
  }
  bool zero = false;
  for (uint32_t m = 10000; m; m /= 10) {
    uint8_t d = (n / m) % 10;
    if (zero)
      *(b++) = d + '0';
    else if (d) {
      zero = true;
      *(b++) = d + '0';
    }
  }
  *b = 0;
}

void u8_dec(uint8_t n, uint8_t *b) {
  if (!n) {
    *(uint16_t *)b = '0';
    return;
  }
  bool zero = false;
  for (uint32_t m = 100; m; m /= 10) {
    uint8_t d = (n / m) % 10;
    if (zero)
      *(b++) = d + '0';
    else if (d) {
      zero = true;
      *(b++) = d + '0';
    }
  }
  *b = 0;
}

void u32_hex(uint32_t n, uint8_t *b) {
  uint8_t m = 28;
  while (1) {
    uint8_t d = (n >> m) & 0xf;
    *(b++) = d >= 10 ? 'a' + d - 10 : '0' + d;
    if (!m) {
      *b = 0;
      return;
    }
    m -= 4;
  }
}

void u16_hex(uint16_t n, uint8_t *b) {
  uint8_t m = 12;
  while (1) {
    uint8_t d = (n >> m) & 0xf;
    *(b++) = d >= 10 ? 'a' + d - 10 : '0' + d;
    if (!m) {
      *b = 0;
      return;
    }
    m -= 4;
  }
}

void u8_hex(uint8_t n, uint8_t *b) {
  uint8_t m = 4;
  while (1) {
    uint8_t d = (n >> m) & 0xf;
    *(b++) = d >= 10 ? 'a' + d - 10 : '0' + d;
    if (!m) {
      *b = 0;
      return;
    }
    m -= 4;
  }
}