トルネード

毛利のメモ書き

std::wstring to byte[]

VC++2015の場合

f:id:mojeld:20161012124745j:plain

#include "stdafx.h"
#include <string>
#include <iostream>
#include <memory>
#include <sstream>
#include <locale>

using Byte = char;
using PByte = std::shared_ptr<Byte>;
PByte WstrToChar(std::wstring& s1)
{
    unsigned int iLength = s1.length() * 2 + 1;
    PByte result_{new Byte[iLength]};
    memcpy(result_.get(), s1.c_str(), iLength);  //wstring to byte[]
    return result_;
}

int main()
{
    std::locale::global(std::locale("japanese"));
    std::wstring ls = L"あいうえお日本語";
    std::wstringstream as1;
    std::string s_out;
    PByte c1 = WstrToChar(ls);
    char* c2 = c1.get();
    for (int i = 0; i < ls.length() * 2; i++)
    {
        int iin = static_cast<int>(*c2);
        if (iin < 0) { iin = iin - 0xffffff00; }//これはなぜ?
        as1 << std::hex << std::showbase << iin << std::endl;
        c2++;
    }
    std::wcout << as1.str();
    std::cin >> s_out;
    return 0;
}

C++Builder 10.1Berlin の場合

using PSByte = std::shared_ptr<Byte>;
PSByte WstrToChar(std::wstring& s1)
{
    unsigned int iLength = s1.length() * 2 + 1;
    PSByte result_{new Byte[iLength]};
    memcpy(result_.get(), s1.c_str(), iLength);  //wstring to byte[]
    return result_;
}

void __fastcall TForm1::FormCreate(TObject *Sender)
{
    std::locale::global(std::locale("japanese"));
    std::wstring ls = L"あいうえお日本語";
    std::wstringstream as1;
    std::string s_out;
    PSByte c1 = WstrToChar(ls);
    Byte* c2 = c1.get();
    for (int i = 0; i < ls.length() * 2; i++)
    {
        as1 << std::hex << std::showbase << static_cast<unsigned int>(*c2) << std::endl;
        c2++;
    }
    Memo1->Lines->Text = as1.str().c_str();

}