2013-08-30 1 views
1

응용 프로그램에서 문자를 UTF-8 인코딩 % C3 % BA (으)로 수신하고 유니 코드 상응하는 % FA로 저장하는 C++ 응용 프로그램에서 U를 어떻게 변환합니까? 난 그냥 ...이 인코딩 과정UTF-8에서 유니 코드로 변환 C++

+3

http://utfcpp.sourceforge.net/? –

+0

http://msdn.microsoft.com/en-us/library/dd374130(v=vs.85).aspx? –

+3

제목과 관련하여 기록을 위해 : UTF-8 _is_ 유니 코드. 코드 포인트를 지정하는 표준 방법은'U + 00FA' (최소 4 자리 16 진수, 최대 6 자리)입니다. –

답변

5

난 그냥이 어제 할 몇 가지 코드를 썼다을 수행하는 코드를 작성 가겠어요 방법을 알고 싶어요

나는이에 "완벽한"방법입니다 말하는 게 아니에요 이렇게해라. 그러나 나는 그것을 실행 한 모든 테스트 케이스들 (나는 그 목적을 위해 두 방향 모두를 썼다)에서 작동하는 것으로 보인다.

"% NN"을 정수 값으로 변환하겠습니다.

#include <iostream> 
#include <deque> 

std::deque<int> unicode_to_utf8(int charcode) 
{ 
    std::deque<int> d; 
    if (charcode < 128) 
    { 
     d.push_back(charcode); 
    } 
    else 
    { 
     int first_bits = 6; 
     const int other_bits = 6; 
     int first_val = 0xC0; 
     int t = 0; 
     while (charcode >= (1 << first_bits)) 
     { 
      { 
       t = 128 | (charcode & ((1 << other_bits)-1)); 
       charcode >>= other_bits; 
       first_val |= 1 << (first_bits); 
       first_bits--; 
      } 
      d.push_front(t); 
     } 
     t = first_val | charcode; 
     d.push_front(t); 
    } 
    return d; 
} 


int utf8_to_unicode(std::deque<int> &coded) 
{ 
    int charcode = 0; 
    int t = coded.front(); 
    coded.pop_front(); 
    if (t < 128) 
    { 
     return t; 
    } 
    int high_bit_mask = (1 << 6) -1; 
    int high_bit_shift = 0; 
    int total_bits = 0; 
    const int other_bits = 6; 
    while((t & 0xC0) == 0xC0) 
    { 
     t <<= 1; 
     t &= 0xff; 
     total_bits += 6; 
     high_bit_mask >>= 1; 
     high_bit_shift++; 
     charcode <<= other_bits; 
     charcode |= coded.front() & ((1 << other_bits)-1); 
     coded.pop_front(); 
    } 
    charcode |= ((t >> high_bit_shift) & high_bit_mask) << total_bits; 
    return charcode; 
} 

int main() 
{ 
    int charcode; 

    for(;;) 
    { 
     std::cout << "Enter unicode value:" << std::endl; 
     std::cin >> charcode; 
     auto x = unicode_to_utf8(charcode); 
     for(auto c : x) 
     { 
      std::cout << "\\x" << std::hex << c << " "; 
     } 
     std::cout << std::endl; 
     int c = utf8_to_unicode(x); 
     std::cout << "reversed:" << std::dec << c << std::hex << " in hex:" << c << std::endl; 
    } 
} 
+0

OP가 다른 길로 가고 싶습니다. 그렇습니까? – john

+0

코드에는 양면 큐에서 유니 코드로, 유니 코드에서 비 큐까지의 두 가지 방향이 포함됩니다. 그것은 단지 "필수"코드가 먼저 발생하지 않습니다, 나는 내 코드를 다시 포맷하지 않을 것입니다 ... –

+1

명명과 관련된 작은 메모; 나는'utf32_to_utf8'과'utf8_to_utf32'라는 이름을 제안합니다. "unicode"라는 단어는 약간 오버로딩되어 때때로 utf-16을 의미하는 것으로 이해됩니다. – avakar

관련 문제