aboutsummaryrefslogtreecommitdiff
path: root/ber/int.go
blob: 41defc8eb048428c19d787a06d1f876ce8b82dca (plain)
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
package ber

func UnmarshalInt(b []byte) (i int) {
	neg := b[0]&0x80 != 0
	for n, v := range b {
		if neg {
			v = ^v
		}
		i += int(v) << uint((len(b)-n-1)*8)
	}
	if neg {
		i = ^i
	}
	return
}

func intLen(i int) (n int) {
	for i > 127 {
		n++
		i >>= 8
	}
	for i < -128 {
		n++
		i >>= 8
	}
	return n + 1
}

func MarshalInt(i int) (b []byte) {
	for n := intLen(i); n > 0; n-- {
		b = append(b, byte(i>>uint((n-1)*8)))
	}
	return
}