bitfield: add bf.from_bytes_lowest_bits_first/1 and a test for it

pull/7402/head
Delyan Angelov 2020-12-18 21:58:42 +02:00
parent c5c310280f
commit f74ab3a52d
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
2 changed files with 20 additions and 2 deletions

View File

@ -24,8 +24,8 @@ const (
slot_size = 32 slot_size = 32
) )
// public functions // from_bytes converts a byte array into a bitfield.
// from_bytes() converts a byte array into a bitfield. // [0x0F, 0x01] => 0000 1111 0000 0001
pub fn from_bytes(input []byte) BitField { pub fn from_bytes(input []byte) BitField {
mut output := new(input.len * 8) mut output := new(input.len * 8)
for i, b in input { for i, b in input {
@ -59,6 +59,16 @@ pub fn from_bytes(input []byte) BitField {
return output return output
} }
// from_bytes_lowest_bits_first converts a byte array into a bitfield
// [0x0F, 0x01] => 1111 0000 1000 0000
pub fn from_bytes_lowest_bits_first(input []byte) BitField {
mut output := new(input.len * 8)
for i, b in input {
output.field[i / 4] |= u32(b) << ((i % 4) * 8)
}
return output
}
// from_str converts a string of characters ('0' and '1') to a bit // from_str converts a string of characters ('0' and '1') to a bit
// array. Any character different from '0' is treated as '1'. // array. Any character different from '0' is treated as '1'.
pub fn from_str(input string) BitField { pub fn from_str(input string) BitField {

View File

@ -126,6 +126,14 @@ fn test_bf_from_bytes() {
assert newoutput == output assert newoutput == output
} }
fn test_bf_from_bytes_lowest_bits_first() {
input := [byte(0x01), 0xF0]
output := bitfield.from_bytes_lowest_bits_first(input).str()
assert output == '10000000' + '00001111'
newoutput := bitfield.from_str(output).str()
assert newoutput == output
}
fn test_bf_from_str() { fn test_bf_from_str() {
len := 80 len := 80
mut input := '' mut input := ''