mirror of https://bitbucket.org/ausocean/av.git
codec/h264/h264dec: added binToInt function and test
This function will convert binary provided as a string and return as int.
This commit is contained in:
parent
614f42ec2c
commit
245edafa68
|
@ -9,6 +9,7 @@ package h264dec
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"math"
|
||||||
)
|
)
|
||||||
|
|
||||||
// binToSlice is a helper function to convert a string of binary into a
|
// binToSlice is a helper function to convert a string of binary into a
|
||||||
|
@ -42,6 +43,21 @@ func binToSlice(s string) ([]byte, error) {
|
||||||
return bytes, nil
|
return bytes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// binToInt converts a binary string provided as a string and returns as an int.
|
||||||
|
// White spaces are ignored.
|
||||||
|
func binToInt(s string) (int, error) {
|
||||||
|
var sum int
|
||||||
|
var nSpace int
|
||||||
|
for i := len(s) - 1; i >= 0; i-- {
|
||||||
|
if s[i] == ' ' {
|
||||||
|
nSpace++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sum += int(math.Pow(2, float64(len(s)-1-i-nSpace))) * int(s[i]-'0')
|
||||||
|
}
|
||||||
|
return sum, nil
|
||||||
|
}
|
||||||
|
|
||||||
func maxi(a, b int) int {
|
func maxi(a, b int) int {
|
||||||
if a > b {
|
if a > b {
|
||||||
return a
|
return a
|
||||||
|
|
|
@ -0,0 +1,28 @@
|
||||||
|
package h264dec
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestBinToInt(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
in string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{in: "101", want: 5},
|
||||||
|
{in: "1", want: 1},
|
||||||
|
{in: "00000", want: 0},
|
||||||
|
{in: "", want: 0},
|
||||||
|
{in: "1111", want: 15},
|
||||||
|
{in: "1 111", want: 15},
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, test := range tests {
|
||||||
|
n, err := binToInt(test.in)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("did not expect error: %v from binToInt", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if n != test.want {
|
||||||
|
t.Errorf("did not get expected result for test %d\nGot: %v\nWant: %v\n", i, n, test.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue