From 738235574f32690f186e4734636434641093c2ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=BCseyin=20ASLIT=C3=9CRK?= Date: Wed, 20 May 2020 21:20:43 +0300 Subject: [PATCH] AK: StringUtils, add "convert_to_uint_from_hex" method New method to convert hex string unsigned integer. --- AK/StringUtils.cpp | 32 ++++++++++++++++++++++++++++++++ AK/StringUtils.h | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/AK/StringUtils.cpp b/AK/StringUtils.cpp index 7f6c6f4a97b..4bd2b7aadaa 100644 --- a/AK/StringUtils.cpp +++ b/AK/StringUtils.cpp @@ -143,6 +143,38 @@ unsigned convert_to_uint(const StringView& str, bool& ok) return value; } +unsigned convert_to_uint_from_hex(const StringView& str, bool& ok) +{ + if (str.is_empty()) { + ok = false; + return 0; + } + + unsigned value = 0; + const auto count = str.length(); + + for (size_t i = 0; i < count; i++) { + char digit = str[i]; + u8 digit_val; + + if (digit >= '0' && digit <= '9') { + digit_val = digit - '0'; + } else if (digit >= 'a' && digit <= 'f') { + digit_val = 10 + (digit - 'a'); + } else if (digit >= 'A' && digit <= 'F') { + digit_val = 10 + (digit - 'A'); + } else { + ok = false; + return 0; + } + + value = (value << 4) + digit_val; + } + + ok = true; + return value; +} + static inline char to_lowercase(char c) { if (c >= 'A' && c <= 'Z') diff --git a/AK/StringUtils.h b/AK/StringUtils.h index f4b433b8ef4..7e9007f102a 100644 --- a/AK/StringUtils.h +++ b/AK/StringUtils.h @@ -41,8 +41,8 @@ namespace StringUtils { bool matches(const StringView& str, const StringView& mask, CaseSensitivity = CaseSensitivity::CaseInsensitive); int convert_to_int(const StringView&, bool& ok); unsigned convert_to_uint(const StringView&, bool& ok); +unsigned convert_to_uint_from_hex(const StringView&, bool& ok); bool equals_ignoring_case(const StringView&, const StringView&); - } }