diff --git a/vlib/bitfield/bitfield.v b/vlib/bitfield/bitfield.v index 99add985d2..73e03ff579 100644 --- a/vlib/bitfield/bitfield.v +++ b/vlib/bitfield/bitfield.v @@ -24,8 +24,8 @@ const ( 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 { mut output := new(input.len * 8) for i, b in input { @@ -59,6 +59,16 @@ pub fn from_bytes(input []byte) BitField { 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 // array. Any character different from '0' is treated as '1'. pub fn from_str(input string) BitField { diff --git a/vlib/bitfield/bitfield_test.v b/vlib/bitfield/bitfield_test.v index b5f4e864fa..7bcc9e7860 100644 --- a/vlib/bitfield/bitfield_test.v +++ b/vlib/bitfield/bitfield_test.v @@ -126,6 +126,14 @@ fn test_bf_from_bytes() { 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() { len := 80 mut input := ''