From ea4118ddeb8238ccc065a2c11237ad7be056f89e Mon Sep 17 00:00:00 2001 From: Zhaohe Date: Tue, 13 Dec 2022 20:14:20 +0800 Subject: [PATCH] update stringutils --- core/components/string_util.cpp | 27 ++++++++++++++++++++++++++- core/components/string_util.hpp | 31 +++++++++++++++++++++++-------- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/core/components/string_util.cpp b/core/components/string_util.cpp index 4d5ced5..2cee45e 100644 --- a/core/components/string_util.cpp +++ b/core/components/string_util.cpp @@ -96,4 +96,29 @@ bool StringUtil::hexStringToBytes(string in, string delims, vector& byt return false; } return true; -} \ No newline at end of file +} + +/** + * @brief + * + * @param value + * @return string + */ +string StringUtil::bytet2Binary(uint32_t value, int bitCount, bool remoteZero) { + string ret; + for (int i = 0; i < bitCount; ++i) { + uint32_t bit = value & 0x01; + value = value >> 1; + if (bit == 0) { + ret = "0" + ret; + } else { + ret = "1" + ret; + } + } + if (remoteZero) { + while (ret[0] == '0') { + ret = ret.substr(1); + } + } + return ret; +} diff --git a/core/components/string_util.hpp b/core/components/string_util.hpp index 35e9e87..eeae046 100644 --- a/core/components/string_util.hpp +++ b/core/components/string_util.hpp @@ -21,24 +21,24 @@ class StringUtil { /** * @brief 替换字符串中的字符,如果new_value="",则删除旧字符 - * - * @param str - * @param old_value - * @param new_value - * @return string& + * + * @param str + * @param old_value + * @param new_value + * @return string& */ string& replaceAllDistinct(string& str, const string& old_value, const string& new_value); /** * @brief 转换HEX字符串成Bytes数组例如 - * + * * // string("12,0a,2a,ab") ===> char buf[] = {0x12,0x0a,0x2a,0xab} * vector tobytes; * hexStringToBytes("12,0a,2a,ab",",",tobytes); - * + * * // string("120a2aab") ===> char buf[] = {0x12,0x0a,0x2a,0xab} * vector tobytes; * hexStringToBytes("120a2aab","",tobytes); - * + * * @param in 输入字符串 * @param delims 分割符 * @param byteTable 输出的byte数组 @@ -46,6 +46,21 @@ class StringUtil { * @return false 转换失败 */ bool hexStringToBytes(string in, string delims, vector& byteTable); + + /** + * @brief + * + * @param value 0x55 + * @param bitCount 8 + * @param remoteZero true/false + * @return string 01010101 + * + * Demo: + * StringUtil::bytet2Binary(0x55,8,true) ===> 1010101 + * StringUtil::bytet2Binary(0x55,8,false) ===> 01010101 + * + */ + string bytet2Binary(uint32_t value, int bitCount, bool remoteZero = true); }; } // namespace core