Skip to content

Instantly share code, notes, and snippets.

@klkyy2020
Last active March 20, 2020 04:53
Show Gist options
  • Save klkyy2020/e785c2520325285909e2dfd54a53e9ab to your computer and use it in GitHub Desktop.
Save klkyy2020/e785c2520325285909e2dfd54a53e9ab to your computer and use it in GitHub Desktop.
// validRange returns false if 0 is between 1 or starts with 0
// otherwise returns true
func validRange(val byte) bool {
v := val
foo := byte(128)
firstBit := true
zeroAppears := false
if v == 0 {
return false
}
for v != 0 {
if int(v&foo) == 0 {
if firstBit {
return false
}
zeroAppears = true
} else {
if zeroAppears {
return false
}
}
v = v << 1
firstBit = false
}
return true
}
func Test_validRange(t *testing.T) {
type args struct {
val byte
}
tests := []struct {
name string
args args
want bool
}{
// {args: args{val: 0}, want: false},
{args: args{val: 1}, want: false},
{args: args{val: 2}, want: false},
{args: args{val: 5}, want: false},
{args: args{val: 127}, want: false},
{args: args{val: 128}, want: true},
{args: args{val: 129}, want: false},
{args: args{val: 192}, want: true},
{args: args{val: 255}, want: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := validRange(tt.args.val); got != tt.want {
t.Errorf("validRange() = %v, want %v", got, tt.want)
}
})
}
}
// countOne return how many 1 in binary form of a byte
func countOne(val byte) int {
v := val
res := 0
for v != 0 {
res += int(v & 1)
v = v >> 1
}
return res
}
func Test_countOne(t *testing.T) {
type args struct {
val byte
}
tests := []struct {
name string
args args
want int
}{
{args: args{val: 0}, want: 0},
{args: args{val: 255}, want: 8},
{args: args{val: 1}, want: 1},
{args: args{val: 2}, want: 1},
{args: args{val: 3}, want: 2},
{args: args{val: 4}, want: 1},
{args: args{val: 5}, want: 2},
{args: args{val: 6}, want: 2},
{args: args{val: 7}, want: 3},
{args: args{val: 8}, want: 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := countOne(tt.args.val); got != tt.want {
t.Errorf("countOne() = %v, want %v", got, tt.want)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment