add utils
This commit is contained in:
parent
b2ff9e4d55
commit
6446d18ee1
84
app/src/main/cpp/utils.h
Normal file
84
app/src/main/cpp/utils.h
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
//
|
||||||
|
// Created by ACER on 2023/02/27.
|
||||||
|
//
|
||||||
|
|
||||||
|
#ifndef CCCC_UTILS_H
|
||||||
|
#define CCCC_UTILS_H
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <random>
|
||||||
|
#include <vector>
|
||||||
|
#include <sstream>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
#include <endian.h>
|
||||||
|
#include <android/log.h>
|
||||||
|
|
||||||
|
#define LOGTAG "CCCC_LOGGER"
|
||||||
|
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOGTAG, __VA_ARGS__)
|
||||||
|
|
||||||
|
typedef std::vector<uint8_t> 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<uint8_t> distribution(
|
||||||
|
std::numeric_limits<uint8_t>::min(),
|
||||||
|
std::numeric_limits<uint8_t>::max());
|
||||||
|
static std::default_random_engine generator;
|
||||||
|
|
||||||
|
std::vector<uint8_t> 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
|
Loading…
Reference in New Issue
Block a user