기본 콘텐츠로 건너뛰기

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)인지 판단한다.

댓글

이 블로그의 인기 게시물

Winget 해시 무시하기

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

Windows 11 기존 컨텍스트 메뉴 사용

Windows 11 에서, 컨텍스트 메뉴가 지저분한게 싫었는지, 모던 컨텍스트 메뉴라고 따로 필요한 것만 정리해서 보여준다. 그러나 이게 좀 불편하고, 기존의 꼭 필요한 메뉴가 보이지 않아 굳이 한 번 더 기존 메뉴를 불러오는데, 모든 앱들이 모던 컨텍스트 메뉴로 옮길 때까지는 기존 컨텍스트 메뉴를 기본으로 볼 수 있는 방법이 있다. REM 관리자 권한 REM 기존 컨텍스트 메뉴 reg.exe add "HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" /f /ve REM 모던 컨텍스트 메뉴로 되돌리기 reg.exe delete "HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}" /f 이거 하고 탐색기를 재시작한다. 참조:  Restore old Right-click Context menu in Windows 11