-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitwriter.c
More file actions
73 lines (50 loc) · 1.34 KB
/
bitwriter.c
File metadata and controls
73 lines (50 loc) · 1.34 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
#include <stdio.h>
#include <stdlib.h>
/* put in bitwriter.c */
#include "bitwriter.h"
#include "io.h"
struct BitWriter {
Buffer *underlying_stream;
uint8_t byte;
uint8_t bit_position;
};
BitWriter *bit_write_open(const char *filename) {
BitWriter *buf = calloc(1, sizeof(BitWriter));
Buffer *underlying_stream = write_open(filename);
buf->underlying_stream = underlying_stream;
return buf;
}
void bit_write_close(BitWriter **pbuf) {
if ((*pbuf)->bit_position > 0) {
write_uint8((*pbuf)->underlying_stream, (*pbuf)->byte);
}
write_close(&(*pbuf)->underlying_stream);
free(*pbuf);
*pbuf = NULL;
}
void bit_write_bit(BitWriter *buf, uint8_t x) {
if (buf->bit_position > 7) {
write_uint8(buf->underlying_stream, buf->byte);
buf->byte = 0x00;
buf->bit_position = 0;
}
if (x & 1) {
buf->byte |= (x & 1) << buf->bit_position;
}
buf->bit_position++;
}
void bit_write_uint8(BitWriter *buf, uint8_t x) {
for (int i = 0; i <= 7; i++) {
bit_write_bit(buf, x >> i);
}
}
void bit_write_uint16(BitWriter *buf, uint16_t x) {
for (int i = 0; i <= 15; i++) {
bit_write_bit(buf, x >> i);
}
}
void bit_write_uint32(BitWriter *buf, uint32_t x) {
for (int i = 0; i <= 31; i++) {
bit_write_bit(buf, x >> i);
}
}