aboutsummaryrefslogtreecommitdiff
path: root/src/utils.c
diff options
context:
space:
mode:
authorLibravatar Comrade Martin Miroslavovich Michalec <martin@michalec.dev>2023-11-25 18:59:53 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-07 02:12:54 +0000
commit055f35e74601bea2223a1555c15b029ee90a9117 (patch)
treec2bc92f254ad85b9fc545ab30a700757d72902fc /src/utils.c
downloadlab-02-master.tar.gz
publishHEADmaster
Diffstat (limited to 'src/utils.c')
-rw-r--r--src/utils.c58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/utils.c b/src/utils.c
new file mode 100644
index 0000000..574a80e
--- /dev/null
+++ b/src/utils.c
@@ -0,0 +1,58 @@
1#include "utils.h"
2#include <stdlib.h>
3#include <stdio.h>
4#include <stdarg.h>
5#include <regex.h>
6#include <string.h>
7
8int
9input (const char *message, const char *regex, const char *template, ...)
10{
11 char *line = NULL;
12 size_t line_size = 0;
13 regex_t compiled;
14 int matches = 0;
15 int c;
16 va_list ap;
17
18 va_start (ap, template);
19 vprintf (message, ap);
20 printf (" (\"%s\"): ", regex);
21 getline (&line, &line_size, stdin);
22 line[strlen (line) - 1] = '\0';
23
24 regcomp (&compiled, regex, REG_EXTENDED | REG_NOSUB);
25 if (regexec (&compiled, line, 0, NULL, 0))
26 goto defer;
27
28 matches = vsscanf (line, template, ap);
29 va_end (ap);
30
31 defer:
32 free (line);
33 return matches;
34}
35
36uint
37log10ui (uint ui)
38{
39 return ((ui >= 1000000000u) ? 9 :
40 (ui >= 100000000u) ? 8 :
41 (ui >= 10000000u) ? 7 :
42 (ui >= 1000000u) ? 6 :
43 (ui >= 100000u) ? 5 :
44 (ui >= 10000u) ? 4 :
45 (ui >= 1000u) ? 3 :
46 (ui >= 100u) ? 2 :
47 (ui >= 10u) ? 1 : 0u);
48}
49
50u16
51rev16 (u16 b)
52{
53 b = (b & 0xFF00) >> 8 | (b & 0x00FF) << 8;
54 b = (b & 0xF0F0) >> 4 | (b & 0x0F0F) << 4;
55 b = (b & 0xCCCC) >> 2 | (b & 0x3333) << 2;
56 b = (b & 0xAAAA) >> 1 | (b & 0x5555) << 1;
57 return b;
58}