From d13c10c6047a02d695c9fb03f7912b7d17844bbd Mon Sep 17 00:00:00 2001 From: Tomasz Sowa Date: Tue, 26 Jul 2022 05:14:35 +0200 Subject: [PATCH] add methods for converting from hex string to bytes add to convert/text.h: template bool hex_string_pointer_to_bytes(const HexStringPointerType * hex_string, BytesStringType & bytes, bool clear_bytes = true); template bool hex_string_to_bytes(const HexStringType & hex_string, BytesStringType & bytes, bool clear_bytes = true); --- src/convert/text.h | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/src/convert/text.h b/src/convert/text.h index 1962d5a..0f73650 100644 --- a/src/convert/text.h +++ b/src/convert/text.h @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2017-2021, Tomasz Sowa + * Copyright (c) 2017-2022, Tomasz Sowa * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -44,6 +44,49 @@ namespace pt bool is_white(wchar_t c, bool check_additional_chars = true, bool treat_new_line_as_white = true); bool is_digit(wchar_t c, int base = 10, int * digit = 0); + +// IMPROVEME add tests +template +bool hex_string_pointer_to_bytes(const HexStringPointerType * hex_string, BytesStringType & bytes, bool clear_bytes = true) +{ + bool converted_correctly = true; + size_t i = 0; + + if( clear_bytes ) + bytes.clear(); + + for( ; converted_correctly && hex_string[i] != 0 && hex_string[i+1] != 0 ; i += 2) + { + int c1, c2; + + converted_correctly = converted_correctly && is_digit(hex_string[i], 16, &c1); + converted_correctly = converted_correctly && is_digit(hex_string[i+1], 16, &c2); + + if( converted_correctly ) + { + bytes += (char)(unsigned char)(((c1 << 4) | c2)); + } + } + + if( hex_string[i] != 0 ) + { + // one digit has left + converted_correctly = false; + } + + return converted_correctly; +} + + +// IMPROVEME add tests +template +bool hex_string_to_bytes(const HexStringType & hex_string, BytesStringType & bytes, bool clear_bytes = true) +{ + return hex_string_pointer_to_bytes(hex_string.c_str(), bytes, clear_bytes); +} + + + const char * skip_white(const char * str, bool check_additional_chars = true, bool treat_new_line_as_white = true); const wchar_t * skip_white(const wchar_t * str, bool check_additional_chars = true, bool treat_new_line_as_white = true);