Skip to content

Instantly share code, notes, and snippets.

@VictorZhang2014
Created March 19, 2017 02:34
Show Gist options
  • Save VictorZhang2014/f7375de5b627b86497ada90043013839 to your computer and use it in GitHub Desktop.
Save VictorZhang2014/f7375de5b627b86497ada90043013839 to your computer and use it in GitHub Desktop.
UTF8 Encoding was written by c++
#include <vector>
#include <codecvt>
std::string VLUtilitiesEncoding::UTF8Encoding(std::string & unencodedStr)
{
if (unencodedStr.length() <= 0) return "";
std::wstring_convert<std::codecvt_utf8<wchar_t>,wchar_t> conversion;
std::wstring wbodyStr = conversion.from_bytes(unencodedStr);
return conversion.to_bytes(wbodyStr);
}
void hexchar(unsigned char c, unsigned char &hex1, unsigned char &hex2)
{
hex1 = c / 16;
hex2 = c % 16;
hex1 += hex1 <= 9 ? '0' : 'a' - 10;
hex2 += hex2 <= 9 ? '0' : 'a' - 10;
}
std::string VLUtilitiesEncoding::URLEncode(std::string s)
{
const char *str = s.c_str();
std::vector<char> v(s.size());
v.clear();
for (size_t i = 0, l = s.size(); i < l; i++)
{
char c = str[i];
if ((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
c == '-' || c == '_' || c == '.' || c == '!' || c == '~' ||
c == '*' || c == '\'' || c == '(' || c == ')')
{
v.push_back(c);
}
else if (c == ' ')
{
v.push_back('+');
}
else
{
v.push_back('%');
unsigned char d1, d2;
hexchar(c, d1, d2);
v.push_back(d1);
v.push_back(d2);
}
}
return std::string(v.cbegin(), v.cend());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment