LoginSignup
0
0

More than 1 year has passed since last update.

M5Paper: utf-16 を utf-8 に変換

Last updated at Posted at 2022-06-14

こちらの記事を参考にしました。
Unicode ( UTF16 ) 文字列を UTF-8 に変換する方法 ( Arduino – ESP32 )

M5Paper で確認しましたが、固有の機能は使ってないので、他の Arduino でも動くと思います。
入力は、リトルエンディアンです。
"ものづくりの根底" の UTF-16 表記は

リトルエンディアン

82306e3065304f308a306e303968955e

ビッグエンディアン

3082306E3065304F308A306E68395E95

プログラム

utf16-utf8.ino
// --------------------------------------------------------------------
//	utf16-utf8.ino
//
//						Jun/14/2022
// --------------------------------------------------------------------
String UTF16toUTF8(String str);
// --------------------------------------------------------------------
void setup()
{
	Serial.begin(115200);
	delay(2000);
	Serial.println("**** unicode ***");
	delay(1000);
	Serial.println("**** Jun/14/2022 ***");
	delay(1000);
	Serial.println("**** test ***");
	delay(1000);
}
 
// --------------------------------------------------------------------
void loop(){
	Serial.println();
	Serial.println("**** PM 14:16 ***\n");
 
 String utf16_str = "82306e3065304f308a306e303968955e";

	Serial.println("【 Unicode ( UTF16 ) 】");
	Serial.println( utf16_str );
	Serial.println("【 UTF16 → UTF8 】");
	Serial.println( UTF16toUTF8( utf16_str ) );
	
	delay(5000);
}
 
// --------------------------------------------------------------------
UTF16toUTF8.cpp
// --------------------------------------------------------------------
//	UTF16toUTF8.cpp
//
//		little endian
//						Jun/14/2022
// --------------------------------------------------------------------
#include <codecvt>
#include <string>
#include <cassert>
#include <locale>
#include <Arduino.h>

// --------------------------------------------------------------------
std::string utf16_to_utf8(std::u16string const& src)
{
	std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter;
	return converter.to_bytes(src);
}

// --------------------------------------------------------------------
String UTF16toUTF8(String str)
{
	str += '\0';
	uint16_t len = str.length();
	char16_t utf16code[len];

	short icount=0;
	for(short jt=0; jt<len; jt+=4)
		{
		std::string  strx = "";
		strx += str[jt+2];
		strx += str[jt+3];
		strx += str[jt+0];
		strx += str[jt+1];
     
		utf16code[icount] = strtol(strx.c_str(), NULL, 16);
				// 16進文字列を16進数値に変換
		icount++;
		}

	for (short it = 0; it < icount; it++)
		{
		Serial.printf("%02x " ,utf16code[it] );
		}
	Serial.println();

	std::u16string u16str(utf16code);
	std::string u8str = utf16_to_utf8(u16str);
	String ret_str = String(u8str.c_str());
 
	return ret_str;
}

// --------------------------------------------------------------------

Arduino IDE

image.png

0
0
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
0