From b2fe5da824728c7f5b12754cbcb4b38d60892683 Mon Sep 17 00:00:00 2001 From: jsnkan Date: Wed, 26 Feb 2025 21:06:20 +0200 Subject: [PATCH] feat: integer to binary array conversion --- api/Binary.cpp | 37 +++++++++++++++++++++++++++++++++++++ api/Binary.h | 3 +++ 2 files changed, 40 insertions(+) create mode 100644 api/Binary.cpp diff --git a/api/Binary.cpp b/api/Binary.cpp new file mode 100644 index 00000000..7b4738d0 --- /dev/null +++ b/api/Binary.cpp @@ -0,0 +1,37 @@ +/* + binary.cpp - Definitions for binary constants + Copyright (c) 2025 jsnkan. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "Binary.h" + +void intToBinaryArray(unsigned char n, int *arr) { + if (arr == 0) return; + for (int i = 7; i >= 0; i--) { + arr[i] = n & 1; + n >>= 1; + } +} + +unsigned char binaryArrayToInt(int *arr) { + if (arr == 0) return 0; + unsigned char n = 0; + for (int i = 0; i < 8; i++) { + n = (n << 1) | (arr[i] & 1); + } + return n; +} \ No newline at end of file diff --git a/api/Binary.h b/api/Binary.h index 947542e3..43d5fc5a 100644 --- a/api/Binary.h +++ b/api/Binary.h @@ -34,6 +34,9 @@ #define DEPRECATED(x) #endif +void intToBinaryArray(unsigned char n, int *arr); +unsigned char binaryArrayToInt(int *arr); + enum { B0 DEPRECATED(0b0 ) = 0, B00 DEPRECATED(0b00 ) = 0,