ucs2 to utf8

Programming/C,C++ 2021. 3. 9. 09:05

#include <stdio.h>

/*

*/
int convert_ucs2_to_utf8(unsigned char* _input_string, unsigned int _input_length, unsigned char* _output_string, unsigned int* _output_length)
{
unsigned short* ucs2 = (unsigned short*) _input_string;
unsigned char* utf8 = (unsigned char*) _output_string;
unsigned int pos = 0;

if (_input_string == NULL || _input_length == 0 || _output_string == NULL || _output_length == NULL) {
// input parameter is wrong
return -1;
}

for (int i = 0; i < (_input_length/2); ++i) {
unsigned short unicode = ucs2[i];

if (unicode < 0x007F) {
utf8[pos + 0] = (unsigned char) unicode;
utf8[pos + 1] = '\0';
pos += 1;
}
else if (unicode < 0x07FF) {
utf8[pos + 0] = (unsigned char)(0xc0 + unicode / (0x01 << 6));
utf8[pos + 1] = (unsigned char)(0x80 + unicode % (0x01 << 6));
utf8[pos + 2] = (unsigned char)'\0';
pos += 2;
}
else {
utf8[pos + 0] = (unsigned char)(0xe0 + unicode / (0x01 << 12));
utf8[pos + 1] = (unsigned char)(0x80 + unicode / (0x01 << 6) % (0x01 << 6));
utf8[pos + 2] = (unsigned char)(0x80 + unicode % (0x01 << 6));
utf8[pos + 3] = (unsigned char)'\0';
pos += 3;
}
}

*_output_length = pos;

return 0;
}

'Programming > C,C++' 카테고리의 다른 글

std::thread example  (0) 2021.09.03
C++ 11, ucs2 to utf8  (0) 2020.08.20
CRC16 ccitt  (0) 2020.07.13
C++ file read binary  (0) 2020.07.12
ModX  (0) 2018.04.28
Posted by 루나s
,