You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何codecvt_utf8转换后的十六进制值前会追加ffffff?

问题原因

这是因为**char在当前编译环境中是有符号类型(signed char)**,而UTF-8编码的é对应的字节是0xC3和0xA9,这两个值都超过了有符号char的最大值0x7F(即127),所以会被解释为负数:

  • 0xC3作为signed char时等价于-61
  • 0xA9作为signed char时等价于-87

当你用static_cast<unsigned>(c)转换时,负数会触发符号扩展:把二进制最高位的符号位(1)填充到所有更高位的字节中,最终32位的unsigned int就变成了0xFFFFFFC3和0xFFFFFFA9,输出自然就带上了ffffff前缀。

解决方法

只需要先把char转换成无符号的unsigned char,再转成unsigned类型,就能避免符号扩展:

ss << std::setw(2) << static_cast<unsigned>(static_cast<unsigned char>(c));

或者更明确的写法:

ss << std::setw(2) << static_cast<unsigned int>(static_cast<unsigned char>(c));

这样处理后,0xC3和0xA9会被当作无符号值直接转换,输出就是预期的c3a9。

内容的提问来源于stack exchange,提问作者user123456

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:30:46