기본 콘텐츠로 건너뛰기

UTF-8 글자마다 바이트 수 세기

UTF-8 문자열에서 문자 하나가 가지는 바이트 수를 구해보자. 요점은 글자 첫 바이트를 찾아 시작점부터 그곳까지 차이를 구하는 것이다.


#include <iostream>
#include <string>
using namespace std;

constexpr auto g_src("한글123ABCabc漢字!@#$^&*()한글123ABCabc漢字");

size_t
getUtf8Size(const uint8_t* ib, const uint8_t* ie)
{
  auto s(ib);

  while ( ++ib not_eq ie )
  {
    if ( ((*ib) bitand 0xc0) not_eq 0x80 ) break;
  }

  return size_t(ib-s);
}

size_t
getUtf8Size(const uint8_t* ib)
{
  auto s(ib);

  while ( *(++ib) )
  {
    if ( ((*ib) bitand 0xc0) not_eq 0x80 ) break;
  }

  return size_t(ib-s);
}

int
main(int argc, char* argv[])
{
  const uint8_t* ib(reinterpret_cast<const uint8_t*>(g_src));
  const uint8_t* ie(ib + strlen(g_src));

  size_t size;

  cout << "Type #1" << endl;
  while ( ib not_eq ie )
  {
    size = getUtf8Size(ib, ie);
    cout << string(reinterpret_cast<const char*>(ib), size) << ": " << size << endl;
    ib+=size;
  }

  cout << "Type #2" << endl;
  ib = reinterpret_cast<const uint8_t*>(g_src);
  while ( *ib )
  {
    size = getUtf8Size(ib);
    cout << string(reinterpret_cast<const char*>(ib), size) << ": " << size << endl;
    ib+=size;
  }
}


별 다를 것은 없고, 주어진 다음 글자에 0xc0(11000000)를 곱해 0x80(10000000)인지 판단한다.

댓글

이 블로그의 인기 게시물

설치한 패키지에서 RPM 추출하기

오래된 패키지를 관리할 저장소가 없어졌고, 기존 패키지로 다른 서버를 세팅해야할 일이 생겼다면 RPM의 리패키지 기능을 이용해보자. $ rpm -e --repackage [PACKAGE_NAME] 위와 같이 리패키지하면, /var/spool/repackage/ 에 생성한 RPM파일이 있다. :-)

Winget 해시 무시하기

가끔씩 Winget 에서 패키지를 다운로드 했을 때, "설치 관리자 해시가 일치하지 않습니다." 오류가 뜰 때가 있다. 보안 이슈가 있지만, 그냥 무시하고 싶을 때, 아래 순서로 무시해준다. 관리자 권한 winget settings --enable InstallerHashOverride 설치 winget install --ignore-security-hash --id NirSoft.NirCmd