rts-sim-module/consts/bit_test.go
walker a0352ee5e8 实现联锁驱采卡系统功能
调整道岔驱动电路逻辑
2023-11-03 17:26:32 +08:00

118 lines
2.5 KiB
Go

package consts
import (
"fmt"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetBitOfBytes(t *testing.T) {
tests := []struct {
give []byte
giveBitIndex int
want bool
wantPanic bool
}{
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 2,
want: false,
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 6,
want: true,
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 8,
want: false,
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 10,
want: false,
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 11,
want: true,
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 16,
wantPanic: true,
},
}
for _, v := range tests {
t.Run(string(v.give), func(t *testing.T) {
if v.wantPanic {
assert.Panics(t, func() { GetBitOfBytes(v.give, v.giveBitIndex) })
} else {
assert.Equal(t, v.want, GetBitOfBytes(v.give, v.giveBitIndex))
}
})
}
}
func TestSetBitOfBytes(t *testing.T) {
tests := []struct {
give []byte
giveBitIndex int
giveVal bool
want []byte
wantPanic bool
}{
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 2,
giveVal: true,
want: []byte{0b00100010, 0b00011111},
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 6,
giveVal: false,
want: []byte{0b00000000, 0b00011111},
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 8,
giveVal: false,
want: []byte{0b00000010, 0b00011111},
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 10,
giveVal: true,
want: []byte{0b00000010, 0b00111111},
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 11,
giveVal: false,
want: []byte{0b00000010, 0b00001111},
},
{
give: []byte{0b00000010, 0b00011111},
giveBitIndex: 16,
wantPanic: true,
},
}
for _, v := range tests {
t.Run(strconv.Itoa(v.giveBitIndex), func(t *testing.T) {
if v.wantPanic {
assert.Panics(t, func() { SetBitOfBytes(v.give, v.giveBitIndex, v.giveVal) })
} else {
assert.Equal(t, v.want, SetBitOfBytes(v.give, v.giveBitIndex, v.giveVal))
}
})
}
}
func TestBitOperation(t *testing.T) {
assert.Equal(t, fmt.Sprintf("%b", 0b11111101), fmt.Sprintf("%b", (1<<(7-6))^0xff))
}