Skip to content

Instantly share code, notes, and snippets.

@kilfu0701
Created October 24, 2019 02:48
Show Gist options
  • Save kilfu0701/e279e35372066ae1832850c438d5611e to your computer and use it in GitHub Desktop.
Save kilfu0701/e279e35372066ae1832850c438d5611e to your computer and use it in GitHub Desktop.
C++ UTF8 to Shift-jis (with ICU)
//
// @reference https://faithandbrave.hateblo.jp/entry/20100318/1268896477
// @memo
// on CentOS:
// yum install libicu libicu-devel
// g++ -std=c++14 -o cvt convert.cpp `pkg-config --libs --cflags icu-uc icu-io`
//
#include <iostream>
#include <vector>
#include <string>
#include <unicode/unistr.h>
std::string
utf8ToSjis(const std::string& value)
{
icu::UnicodeString src(value.c_str(), "utf8");
int length = src.extract(0, src.length(), NULL, "shift_jis");
std::vector<char> result(length + 1);
src.extract(0, src.length(), &result[0], "shift_jis");
return std::string(result.begin(), result.end() - 1);
}
std::string
sjisToUtf8(const std::string& value)
{
icu::UnicodeString src(value.c_str(), "shift_jis");
int length = src.extract(0, src.length(), NULL, "utf8");
std::vector<char> result(length + 1);
src.extract(0, src.length(), &result[0], "utf8");
return std::string(result.begin(), result.end() - 1);
}
int main(int argc, char *argv[])
{
std::string input_string = "テストです!";
std::cout << "input_string = " << input_string << std::endl;
std::string converted_string = utf8ToSjis(input_string);
std::cout << "converted_string = " << converted_string << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment