Convert wchar_t to char

后端 未结 9 1617
谎友^
谎友^ 2020-12-13 04:19

I was wondering is it safe to do so?

wchar_t wide = /* something */;
assert(wide >= 0 && wide < 256 &&);
char myChar = static_cast

        
9条回答
  •  没有蜡笔的小新
    2020-12-13 04:22

    A short function I wrote a while back to pack a wchar_t array into a char array. Characters that aren't on the ANSI code page (0-127) are replaced by '?' characters, and it handles surrogate pairs correctly.

    size_t to_narrow(const wchar_t * src, char * dest, size_t dest_len){
      size_t i;
      wchar_t code;
    
      i = 0;
    
      while (src[i] != '\0' && i < (dest_len - 1)){
        code = src[i];
        if (code < 128)
          dest[i] = char(code);
        else{
          dest[i] = '?';
          if (code >= 0xD800 && code <= 0xD8FF)
            // lead surrogate, skip the next code unit, which is the trail
            i++;
        }
        i++;
      }
    
      dest[i] = '\0';
    
      return i - 1;
    
    }
    

提交回复
热议问题