diff options
| -rw-r--r-- | meson.build | 5 | ||||
| -rw-r--r-- | src/lisiblestd/bytes.c | 24 | ||||
| -rw-r--r-- | src/lisiblestd/bytes.h | 11 | ||||
| -rw-r--r-- | tests/bytes.c | 10 | ||||
| -rw-r--r-- | tests/test.h | 1 |
5 files changed, 50 insertions, 1 deletions
diff --git a/meson.build b/meson.build index f5e724d..b07c672 100644 --- a/meson.build +++ b/meson.build @@ -4,9 +4,12 @@ lisiblestd_incdir = include_directories('src/') lisiblestd_lib = library('lisiblestd', 'src/lisiblestd/log.c', 'src/lisiblestd/memory.c', - 'src/lisiblestd/string.c' + 'src/lisiblestd/string.c', + 'src/lisiblestd/bytes.c' ) lisiblestd_dep = declare_dependency(include_directories: lisiblestd_incdir, link_with: [lisiblestd_lib]) test_string = executable('test_string', 'tests/test_runner.c', 'tests/string.c', dependencies: [lisiblestd_dep]) test('test_string', test_string) +test_bytes = executable('test_bytes', 'tests/test_runner.c', 'tests/bytes.c', dependencies: [lisiblestd_dep]) +test('test_bytes', test_bytes) diff --git a/src/lisiblestd/bytes.c b/src/lisiblestd/bytes.c new file mode 100644 index 0000000..0860800 --- /dev/null +++ b/src/lisiblestd/bytes.c @@ -0,0 +1,24 @@ +#include "bytes.h" +#include "assert.h" +#include <string.h> + +u32 u32_from_bytes(const u8 *bytes) { + LSTD_ASSERT(bytes != NULL); + return (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3]; +} +u32 u32_from_bytes_le(const u8 *bytes) { + LSTD_ASSERT(bytes != NULL); + return (bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0]; +} + +u16 u16_from_bytes_le(const u8 *bytes) { + LSTD_ASSERT(bytes != NULL); + return (bytes[1] << 8) + bytes[0]; +} + +float float_from_bytes_le(const u8 *bytes) { + LSTD_ASSERT(bytes != NULL); + float result; + memcpy(&result, bytes, sizeof(float)); + return result; +} diff --git a/src/lisiblestd/bytes.h b/src/lisiblestd/bytes.h new file mode 100644 index 0000000..8af109b --- /dev/null +++ b/src/lisiblestd/bytes.h @@ -0,0 +1,11 @@ +#ifndef LSTD_BYTES_H +#define LSTD_BYTES_H + +#include "types.h" + +u32 u32_from_bytes(const u8 *bytes); +u32 u32_from_bytes_le(const u8 *bytes); +u16 u16_from_bytes_le(const u8 *bytes); +float float_from_bytes_le(const u8 *bytes); + +#endif // LSTD_BYTES_H diff --git a/tests/bytes.c b/tests/bytes.c new file mode 100644 index 0000000..2d6f95b --- /dev/null +++ b/tests/bytes.c @@ -0,0 +1,10 @@ +#include "test.h" +#include <lisiblestd/bytes.h> + +void t_float_from_bytes_le(void) { + const u8 bytes[4] = {154, 153, 137, 64}; + float number = float_from_bytes_le(bytes); + T_ASSERT_FLOAT_EQ(number, 4.3, 0.01); +} + +TEST_SUITE(TEST(t_float_from_bytes_le)) diff --git a/tests/test.h b/tests/test.h index 223abf5..b81936c 100644 --- a/tests/test.h +++ b/tests/test.h @@ -1,6 +1,7 @@ #ifndef LSTD_TESTS_TEST_H #define LSTD_TESTS_TEST_H +#include <math.h> // IWYU pragma: keep #include <stdarg.h> #include <stdbool.h> #include <stdio.h> |
