-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbits.h
107 lines (92 loc) · 1.7 KB
/
bits.h
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
/*
Read and write bits
Copyright 2021 Ahmet Inan <xdsopl@gmail.com>
*/
#pragma once
#include "bytes.h"
struct bits_reader {
struct bytes_reader *bytes;
int acc;
int cnt;
};
struct bits_writer {
struct bytes_writer *bytes;
int acc;
int cnt;
};
struct bits_reader *bits_reader(struct bytes_reader *bytes)
{
struct bits_reader *bits = malloc(sizeof(struct bits_reader));
bits->bytes = bytes;
bits->acc = 0;
bits->cnt = 0;
return bits;
}
struct bits_writer *bits_writer(struct bytes_writer *bytes)
{
struct bits_writer *bits = malloc(sizeof(struct bits_writer));
bits->bytes = bytes;
bits->acc = 0;
bits->cnt = 0;
return bits;
}
int bits_count(struct bits_writer *bits)
{
return bits->cnt + 8 * bytes_count(bits->bytes);
}
void close_bits_reader(struct bits_reader *bits)
{
free(bits);
}
void close_bits_writer(struct bits_writer *bits)
{
if (bits->cnt)
put_byte(bits->bytes, bits->acc);
free(bits);
}
int put_bit(struct bits_writer *bits, int b)
{
bits->acc |= !!b << bits->cnt++;
if (bits->cnt >= 8) {
bits->cnt -= 8;
int b = bits->acc;
bits->acc >>= 8;
return put_byte(bits->bytes, b);
}
return 0;
}
int write_bits(struct bits_writer *bits, int b, int n)
{
for (int i = 0; i < n; ++i) {
int ret = put_bit(bits, (b >> i) & 1);
if (ret)
return ret;
}
return 0;
}
int get_bit(struct bits_reader *bits)
{
if (!bits->cnt) {
int b = get_byte(bits->bytes);
if (b < 0)
return b;
bits->acc = b;
bits->cnt = 8;
}
int b = bits->acc & 1;
bits->acc >>= 1;
bits->cnt -= 1;
return b;
}
int read_bits(struct bits_reader *bits, int *b, int n)
{
int a = 0;
for (int i = 0; i < n; ++i) {
int b = get_bit(bits);
if (b < 0)
return b;
a |= b << i;
}
*b = a;
return 0;
}