From 76e0c6b31d365978e8ef40e767f518cc170d9713 Mon Sep 17 00:00:00 2001 From: Gabriel Tofvesson Date: Thu, 12 Oct 2017 00:17:43 +0200 Subject: [PATCH] Added hex parser Added support for direct (not shortened) hex parsing --- CPPTools/Support.cpp | 33 +++++++++++++++++++++++++++------ CPPTools/Support.h | 3 +++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/CPPTools/Support.cpp b/CPPTools/Support.cpp index c019f03..3b7ee7d 100644 --- a/CPPTools/Support.cpp +++ b/CPPTools/Support.cpp @@ -76,14 +76,18 @@ namespace Tools { return c; } - char* toHexString(const void* data, ulong_64b size) { + char* toHexString(const void* data, ulong_64b size, bool ignorePreZero) { char* c = (char*)data; - ulong_64b lastNonZero = 0; - for (ulong_64b t = size; t > 0; --t) if (c[t - 1] != 0) { - lastNonZero = t - 1; - goto Ayy; + ulong_64b lastNonZero = ignorePreZero?0:size-1; + if (ignorePreZero) { + for (ulong_64b t = size; t > 0; --t) + if (c[t - 1] != 0) { + lastNonZero = t - 1; + goto Ayy; + } } + else goto Ayy; return new char[2]{ '0', 0 }; Ayy: @@ -102,7 +106,24 @@ namespace Tools { return c1; } - char* toHexString(ulong_64b value) { return toHexString(&value, sizeof(value)); } + char* toHexString(const void* data, ulong_64b size) { return toHexString(data, size, true); } + + char* toHexString(ulong_64b value) { return toHexString(&value, sizeof(value), false); } + + void* parseHex(char* c, size_t *rSize) { + size_t len = strlen(c); + size_t rem = (len % 2); + size_t target = (len + rem) / 2; + if (rSize != nullptr) *rSize = target; + char* out = new char[target]; + if (rem) out[target - 1] = c[0] - (c[0]>64 ? 55 : 48); + for (size_t t = rem; t < len; ++t) { + out[target - 1 - ((t + rem) / 2)] |= (c[t] - (c[t] > 64 ? 55 : 48)) << (((t + 1) % 2) * 4); + } + return out; + } + + ulong_64b parseHexLong(char* c) { return *(ulong_64b*)parseHex(c, nullptr); } bool isDigit(char c) { return (c > 47) && (c < 58); } diff --git a/CPPTools/Support.h b/CPPTools/Support.h index 40c6514..1c94e58 100644 --- a/CPPTools/Support.h +++ b/CPPTools/Support.h @@ -20,8 +20,11 @@ namespace Tools { ulong_64b indexOf(char*, char); ulong_64b lastIndexOf(char*, char); char* copydata(const char*, ulong_64b); + char* toHexString(const void* data, ulong_64b size, bool); char* toHexString(const void* data, ulong_64b size); char* toHexString(ulong_64b); + void* parseHex(char*, size_t *rSize); + ulong_64b parseHexLong(char*); bool isDigit(char c); bool isNumber(char* c); bool isIP(char* c);