forked from nareix/bits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
golomb_reader.go
65 lines (59 loc) · 1.06 KB
/
golomb_reader.go
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
package bits
import (
"io"
)
type GolombBitReader struct {
R io.Reader
buf [1]byte
left byte
}
func (self *GolombBitReader) ReadBit() (res uint, err error) {
if self.left == 0 {
if _, err = self.R.Read(self.buf[:]); err != nil {
return
}
self.left = 8
}
self.left--
res = uint(self.buf[0]>>self.left) & 1
return
}
func (self *GolombBitReader) ReadBits(n int) (res uint, err error) {
for i := 0; i < n; i++ {
var bit uint
if bit, err = self.ReadBit(); err != nil {
return
}
res |= bit << uint(n-i-1)
}
return
}
func (self *GolombBitReader) ReadExponentialGolombCode() (res uint, err error) {
i := 0
for {
var bit uint
if bit, err = self.ReadBit(); err != nil {
return
}
if !(bit == 0 && i < 32) {
break
}
i++
}
if res, err = self.ReadBits(i); err != nil {
return
}
res += (1 << uint(i)) - 1
return
}
func (self *GolombBitReader) ReadSE() (res uint, err error) {
if res, err = self.ReadExponentialGolombCode(); err != nil {
return
}
if res&0x01 != 0 {
res = (res + 1) / 2
} else {
res = -res / 2
}
return
}