From b9378f0b0bbe5ced646d47aa888a6ea214e1823b Mon Sep 17 00:00:00 2001 From: Matthijs Lavrijsen Date: Sat, 10 Oct 2020 01:16:32 +0200 Subject: [PATCH] Add UTF-8/UTF-16 string conversion functions (taken from x64dbg) --- GleeBug/stringutils.cpp | 42 +++++++++++++++++++++++++++++++++++++++++ GleeBug/stringutils.h | 16 ++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 GleeBug/stringutils.cpp create mode 100644 GleeBug/stringutils.h diff --git a/GleeBug/stringutils.cpp b/GleeBug/stringutils.cpp new file mode 100644 index 0000000..6dd779a --- /dev/null +++ b/GleeBug/stringutils.cpp @@ -0,0 +1,42 @@ +#include "stringutils.h" +#include +#include +#include + +// Functions from x64dbg project: https://github.com/x64dbg/x64dbg +//Conversion functions taken from: http://www.nubaria.com/en/blog/?p=289 +String Utf16ToUtf8(const WString & wstr) +{ + String convertedString; + int requiredSize = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, 0, 0, 0, 0); + if(requiredSize > 0) + { + std::vector buffer(requiredSize); + WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &buffer[0], requiredSize, 0, 0); + convertedString.assign(buffer.begin(), buffer.end() - 1); + } + return convertedString; +} + +String Utf16ToUtf8(const wchar_t* wstr) +{ + return Utf16ToUtf8(wstr ? WString(wstr) : WString()); +} + +WString Utf8ToUtf16(const String & str) +{ + WString convertedString; + int requiredSize = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, 0, 0); + if(requiredSize > 0) + { + std::vector buffer(requiredSize); + MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &buffer[0], requiredSize); + convertedString.assign(buffer.begin(), buffer.end() - 1); + } + return convertedString; +} + +WString Utf8ToUtf16(const char* str) +{ + return Utf8ToUtf16(str ? String(str) : String()); +} diff --git a/GleeBug/stringutils.h b/GleeBug/stringutils.h new file mode 100644 index 0000000..8959373 --- /dev/null +++ b/GleeBug/stringutils.h @@ -0,0 +1,16 @@ +#ifndef _STRINGUTILS_H +#define _STRINGUTILS_H + +#include +#include + +typedef std::string String; +typedef std::wstring WString; + + +String Utf16ToUtf8(const WString & wstr); +String Utf16ToUtf8(const wchar_t* wstr); +WString Utf8ToUtf16(const String & str); +WString Utf8ToUtf16(const char* str); + +#endif //_STRINGUTILS_H \ No newline at end of file