From f30b0f1017c2b8ecaf4e02e334ee5a8e234f27b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Silvan=20B=C3=BCdenbender?= <42788329+SilvanCodes@users.noreply.github.com> Date: Wed, 13 Nov 2019 17:48:00 +0100 Subject: [PATCH] bitfield: add from_bytes() function --- vlib/bitfield/bitfield.v | 26 ++++++++++++++++++++++++++ vlib/bitfield/bitfield_test.v | 14 ++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/vlib/bitfield/bitfield.v b/vlib/bitfield/bitfield.v index 85cd4b33c2..f0fd188af8 100644 --- a/vlib/bitfield/bitfield.v +++ b/vlib/bitfield/bitfield.v @@ -77,6 +77,32 @@ fn cleartail(instance mut BitField) { // public functions +// from_bytes() converts a byte arry into a bitfield. +// Be aware of possible trailing zeroes being added +// due to the underlying 32bit int containers. +pub fn from_bytes(input []byte) BitField { + mut output := new(input.len * 8) + for i, b in input { + pos := i / 4 + match i % 4 { + 0 { + output.field[pos] = output.field[pos] | (u32(b) << 24) + } + 1 { + output.field[pos] = output.field[pos] | (u32(b) << 16) + } + 2 { + output.field[pos] = output.field[pos] | (u32(b) << 8) + } + 3 { + output.field[pos] = output.field[pos] | u32(b) + } + } + } + + return output +} + // str2bf() converts a string of characters ('0' and '1') to a bit // array. Any character different from '0' is treated as '1'. diff --git a/vlib/bitfield/bitfield_test.v b/vlib/bitfield/bitfield_test.v index 4c091eb9f3..e7a6d456a6 100644 --- a/vlib/bitfield/bitfield_test.v +++ b/vlib/bitfield/bitfield_test.v @@ -122,6 +122,20 @@ fn test_hamming() { assert count == bitfield.hamming(input1, input2) } +fn test_bf_from_bytes() { + input := [byte(0xF0), byte(0x0F), byte(0xF0), byte(0xFF)] + output := bitfield.from_bytes(input) + mut result := 1 + for i := 0; i < input.len * 8; i++ { + expected := input[input.len - 1 - i / 8] >> i % 8 & 1 + actual := output.getbit(i) + if expected != actual { + result = 0 + } + } + assert result == 1 +} + fn test_bf_str2bf() { rand.seed(time.now().uni) len := 80