From 6446d18ee1ca8ae08af871d8e5e66e9fe36471e0 Mon Sep 17 00:00:00 2001 From: nganhkhoa Date: Wed, 1 Mar 2023 10:51:59 +0700 Subject: [PATCH] add utils --- app/src/main/cpp/utils.h | 84 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 app/src/main/cpp/utils.h diff --git a/app/src/main/cpp/utils.h b/app/src/main/cpp/utils.h new file mode 100644 index 0000000..71e1fdb --- /dev/null +++ b/app/src/main/cpp/utils.h @@ -0,0 +1,84 @@ +// +// Created by ACER on 2023/02/27. +// + +#ifndef CCCC_UTILS_H +#define CCCC_UTILS_H + +#include +#include +#include +#include +#include +#include + +#include +#include + +#define LOGTAG "CCCC_LOGGER" +#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOGTAG, __VA_ARGS__) + +typedef std::vector bytes; + +inline bytes randomBytes(size_t length) { + // We use static in order to instantiate the random engine + // and the distribution once only. + // It may provoke some thread-safety issues. + static std::uniform_int_distribution distribution( + std::numeric_limits::min(), + std::numeric_limits::max()); + static std::default_random_engine generator; + + std::vector data(length); + std::generate(data.begin(), data.end(), []() { return distribution(generator); }); + return data; +} + +inline void logBytes(char* msg, const bytes& data) { + unsigned char charmap[] = { + '0', '1', '2', '3', + '4', '5', '6', '7', + '8', '9', 'A', 'B', + 'C', 'D', 'E', 'F' + }; + std::string stream; + for (size_t i = 0; i < data.size(); i++) { + stream += charmap[(data[i] >> 4)]; + stream += charmap[data[i] & 0x0f]; + } + LOGI(msg, stream.c_str()); +} + +inline uint64_t bytes2num(bytes data) { + uint64_t num = 0; + num = std::accumulate(data.begin(), data.end(), num, + [](uint64_t l, uint8_t r) { + return (l << 8) | r; + }); + return num; +} + +inline bytes num2bytes(uint64_t num) { + bytes r; + uint8_t *b = (uint8_t *) # + for (size_t i = 0; i < 8; i++) { +#ifdef __ARMEB__ + r.push_back(b[i]); +#else + r.push_back(b[7 - i]); +#endif + } + return r; +} + +inline uint bytecount(uint64_t num) { + // find the least byte needed for num + uint count = 0; + while (num != 0) { + count++; + num >>= 8; + } + return count; +} + +#endif //CCCC_UTILS_H