-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.h
More file actions
82 lines (72 loc) · 1.24 KB
/
code.h
File metadata and controls
82 lines (72 loc) · 1.24 KB
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
/* code.h: stack of bits
*
* Author: Darrell Long
* Course: CMPS 12B Spring 2017
* Date: 05/23/17
*/
# ifndef _CODE_H
# define _CODE_H
# include <stdint.h>
# include <stdbool.h>
typedef struct code
{
uint8_t bits[32]; // array of 32 bytes
uint32_t l; // current number of bits
} code;
static inline code newCode()
{
code t;
for (int i = 0; i < 32; i += 1)
{
t.bits[i] = 0;
}
t.l = 0;
return t;
}
static inline bool pushCode(code *c, uint32_t k)
{
if (c->l > 256) // max number of bits reached
{
return false;
}
else if (k == 0) // clear bit
{
c->bits[c->l / 8] &= ~(0x1 << (c->l % 8));
}
else // set bit
{
c->bits[c->l / 8] |= (0x1 << (c->l % 8));
}
c->l += 1;
return true;
}
static inline bool popCode(code *c, uint32_t *k)
{
if (c->l == 0) // nothing to pop
{
return false;
}
else // set k to value of popped bit
{
c->l -= 1;
*k = ((0x1 << (c->l % 8)) & c->bits[c->l / 8]) >> (c->l % 8);
return true;
}
}
static inline bool emptyCode(code *c)
{
return c->l == 0;
}
static inline bool fullCode(code *c)
{
return c->l == 256;
}
static inline void printCode(const code c)
{
for (uint32_t i = 0; i < c.l; i += 1)
{
uint8_t val = ((0x1 << (i % 8)) & c.bits[i / 8]) >> (i % 8);
printf("%u", val);
}
}
# endif