From e55aa58d419fcadcfd7975b9c9c87bf48ef1bd13 Mon Sep 17 00:00:00 2001 From: SamerKhshiboun Date: Sun, 17 Mar 2024 21:12:27 +0200 Subject: [PATCH] add byte manipulation functions --- .../include/rsutils/byte-manipulation.h | 13 +++++++ third-party/rsutils/src/byte-manipulation.cpp | 36 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 third-party/rsutils/include/rsutils/byte-manipulation.h create mode 100644 third-party/rsutils/src/byte-manipulation.cpp diff --git a/third-party/rsutils/include/rsutils/byte-manipulation.h b/third-party/rsutils/include/rsutils/byte-manipulation.h new file mode 100644 index 00000000000..50adf99c6f4 --- /dev/null +++ b/third-party/rsutils/include/rsutils/byte-manipulation.h @@ -0,0 +1,13 @@ +// License: Apache 2.0. See LICENSE file in root directory. +// Copyright(c) 2023 Intel Corporation. All Rights Reserved. + +#pragma once + +namespace rsutils +{ + namespace byte + { + unsigned char reverse_bits(unsigned char b); + void reverse_byte_array_bits(unsigned char* byte_array, int size); + } +} \ No newline at end of file diff --git a/third-party/rsutils/src/byte-manipulation.cpp b/third-party/rsutils/src/byte-manipulation.cpp new file mode 100644 index 00000000000..d442f988da4 --- /dev/null +++ b/third-party/rsutils/src/byte-manipulation.cpp @@ -0,0 +1,36 @@ +// License: Apache 2.0. See LICENSE file in root directory. +// Copyright(c) 2024 Intel Corporation. All Rights Reserved. + +#include + +namespace rsutils +{ + namespace byte + { + // A helper function that takes a byte and reverses its bits + // e.g. intput: 00110101 output: 10101100 + + // First the left four bits are swapped with the right four bits. + // Then all adjacent pairs are swapped and then all adjacent single bits. + // This results in a reversed order. + unsigned char reverse_bits(unsigned char b) + { + b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; + b = (b & 0xCC) >> 2 | (b & 0x33) << 2; + b = (b & 0xAA) >> 1 | (b & 0x55) << 1; + return b; + } + + // A helper function that takes a byte rray of a given size, + // and reverses the bits order of for each byte of this array + // e.g. intput: byteArray = {byte0=00110101, byte1=11110000}, size = 2 + // output: byteArray [ byte0=10101100, byte1=00001111] + void reverse_byte_array_bits(unsigned char* byte_array, int size) { + for (int i = 0; i < size; ++i) + { + byte_array[i] = reverse_bits(byte_array[i]); + } + } + } +} +