97 lines
1.7 KiB
C++
Executable File
97 lines
1.7 KiB
C++
Executable File
// TJP COPYRIGHT HEADER
|
|
|
|
#ifdef TJP_CORE_HEADER_ONLY
|
|
#pragma once
|
|
#endif
|
|
|
|
#include <tjp/core/header_only/compile.h>
|
|
|
|
#include "Base16.h"
|
|
|
|
#include <resolv.h>
|
|
#include <memory.h>
|
|
#include <assert.h>
|
|
|
|
#include <tjp/core/assert/debug_assert.h>
|
|
#include <tjp/core/assert/handle_assert.hpp>
|
|
|
|
namespace tjp::core {
|
|
|
|
using b16d = b16_bin;
|
|
|
|
TJP_CORE_HEADER_ONLY_INLINE
|
|
size_t toBase16 (const b16d *in, size_t inSize, b16_char *out, size_t outSize)
|
|
{
|
|
const char *base16_charset = "0123456789abcdef";
|
|
|
|
handle_assert(outSize == 2 * inSize) {
|
|
return 0;
|
|
}
|
|
|
|
auto begin = in;
|
|
auto end = in + inSize;
|
|
|
|
for (auto *i = begin; i!=end; ++i)
|
|
{
|
|
int n1 = (int)*i & 0x0F;
|
|
int n2 = (int)*i >> 4 & 0x0F;
|
|
|
|
*out++ = base16_charset[n2];
|
|
*out++ = base16_charset[n1];
|
|
}
|
|
|
|
return 2*inSize;
|
|
}
|
|
|
|
TJP_CORE_HEADER_ONLY_INLINE
|
|
std::string toBase16 (const b16d *dataToEncode, size_t dataToEncodeLength)
|
|
{
|
|
std::string encodedData;
|
|
encodedData.resize(dataToEncodeLength*2);
|
|
|
|
toBase16(dataToEncode, dataToEncodeLength, encodedData.data(), encodedData.size());
|
|
|
|
return encodedData;
|
|
}
|
|
|
|
|
|
inline int getNibble (char c)
|
|
{
|
|
if (c >= '0' && c <= '9')
|
|
return c - '0';
|
|
if (c >= 'a' && c <= 'f')
|
|
return c - 'a' + 10;
|
|
if (c >= 'A' && c <= 'F')
|
|
return c - 'A' + 10;
|
|
|
|
handle_assert(false)
|
|
;
|
|
|
|
return 0;
|
|
}
|
|
|
|
TJP_CORE_HEADER_ONLY_INLINE
|
|
size_t fromBase16 (const char *in, size_t inSize, b16d *out, size_t outSize)
|
|
{
|
|
handle_assert((inSize % 2 == 0) && (inSize == 2 * outSize)) {
|
|
return 0;
|
|
}
|
|
|
|
auto begin = in;
|
|
auto end = in + inSize;
|
|
|
|
for (auto *i = begin; i!=end; )
|
|
{
|
|
int n2 = getNibble(*i++);
|
|
int n1 = getNibble(*i++);
|
|
|
|
unsigned char c = n2 << 4 | n1;
|
|
|
|
*out++ = c;
|
|
}
|
|
|
|
return outSize;
|
|
}
|
|
|
|
} // namespace
|