LoginSignup
0
1

More than 1 year has passed since last update.

Windowsで文字コード変換

Last updated at Posted at 2022-06-25

Windowsで文字コード変換するクラス。探したらいっぱい出てくるやつです。

EncodingConverter.h
#pragma once
#include <string>

class EncodingConverter
{
public:
	static std::string SJISToUTF8(std::string src);
	static std::string UTF8ToSJIS(std::string src);
};
EncodingConverter.cpp
#include "EncodingConverter.h"
#include <Windows.h>
#include <string>
#include <vector>

static std::wstring ConvertToUnicode(UINT cp, std::string src)
{
    const DWORD dwFlags = 0;
    const int srcLength = static_cast<int>(src.length());
    const int dstLength = MultiByteToWideChar(cp, dwFlags, src.c_str(), srcLength, NULL, 0);
    if (dstLength <= 0) return L"";

    std::vector<wchar_t> dst(dstLength + 1);
    MultiByteToWideChar(cp, dwFlags, src.c_str(), srcLength, &dst[0], dstLength);
    return std::wstring(&dst[0], dstLength);
}

static std::string ConvertFromUnicode(UINT cp, std::wstring src)
{
    const DWORD dwFlags = 0;
    const int srcLength = static_cast<int>(src.length());
    const int dstLength = WideCharToMultiByte(cp, dwFlags, src.c_str(), srcLength, NULL, 0, NULL, NULL);
    if (dstLength <= 0) return "";

    std::vector<char> dst(dstLength + 1);
    WideCharToMultiByte(cp, dwFlags, src.c_str(), srcLength, &dst[0], dstLength, NULL, NULL);
    return std::string(&dst[0], dstLength);
}

std::string EncodingConverter::SJISToUTF8(std::string src)
{
    std::wstring unicode(ConvertToUnicode(CP_THREAD_ACP, src));
    return std::string(ConvertFromUnicode(CP_UTF8, unicode));
}

std::string EncodingConverter::UTF8ToSJIS(std::string src)
{
    std::wstring unicode(ConvertToUnicode(CP_UTF8, src));
    return std::string(ConvertFromUnicode(CP_THREAD_ACP, unicode));
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1