char类型与Unicode

本文通过Java代码演示了Unicode编码在Java中的使用方式。通过几个简单的示例,文章展示了如何将字符转换为Unicode编码,并解释了Unicode编码对于非空字符串的特殊处理方式。

char tempchar = '我';
System.out.println(Integer.toHexString((int)tempchar));
tempchar = 'i';
System.out.println(Integer.toHexString((int)tempchar));
String temp = "我i";
byte[] bb = temp.getBytes("unicode");
for(byte b:bb){
System.out.println(Integer.toHexString(b));
}
int i = (bb[3]&((1<<8)-1))+((bb[2]&((1<<8)-1))<<8);
System.out.println(Integer.toHexString(i));
System.out.println((char)i);


输出

6211
69
fffffffe
ffffffff
62
11
0
69
6211


从上面可以看出:
1 Java的char使用unicode编码;
2 Unicode编码解析非空字符串的话,前两位byte总是-2,-1
在 C++ 中将 `const char*` 类型的字符串转换为 Unicode 编码(宽字符,通常是 UTF-16 或 UCS-2),可以通过 Windows API 或标准库函数来实现。以下是几种常见方式: ### 使用 Windows API 实现 ANSI 到 Unicode 的转换 在 Windows 平台下,可以使用 `MultiByteToWideChar` 函数进行编码转换。假设输入的 `const char*` 字符串是 ANSI 编码,可将其转换为宽字符字符串。 ```cpp #include <windows.h> #include <string> std::wstring ANSIToUnicode(const std::string& str) { int wstr_size = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0); std::wstring wstr(wstr_size, 0); MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, &wstr[0], wstr_size); return wstr; } ``` 此方法适用于 Windows 平台下的 ANSI 字符串到 Unicode 的转换 [^3]。 --- ### 使用标准 C 库函数 `mbstowcs` 转换 如果希望使用更通用的方法而不依赖平台特定的 API,可以使用 `<cstdlib>` 中的 `mbstowcs` 函数进行多字节字符串到宽字符字符串的转换。 ```cpp #include <cstdlib> #include <string> std::wstring ANSIToUnicodeStd(const std::string& str) { size_t len = mbstowcs(nullptr, str.c_str(), 0); std::wstring wstr(len, L'\0'); mbstowcs(&wstr[0], str.c_str(), len + 1); return wstr; } ``` 该方法不依赖于 Windows API,适用于跨平台项目中对 ANSI 字符串的处理 [^2]。 --- ### 使用 ICU 库进行 UTF-8 到 Unicode 的转换 若 `const char*` 是 UTF-8 编码的字符串,推荐使用 ICU(International Components for Unicode)库进行转换。ICU 提供了强大的 Unicode 支持,适合处理复杂的国际化需求。 ```cpp #include <unicode/unistr.h> #include <string> std::wstring UTF8ToUnicodeICU(const std::string& str) { icu::UnicodeString ustr = icu::UnicodeString::fromUTF8(str); std::wstring wstr(ustr.length(), L'\0'); ustr.extract(0, ustr.length(), wstr.data()); return wstr; } ``` 此方法适用于需要处理 UTF-8 字符串并转换为 Unicode 的场景 [^1]。 --- ### 在 MFC 中自动转换 CString 和 const char* MFC 中的 `CString` 类已经内置了编码转换机制,例如通过重载赋值运算符支持从 `LPCSTR` 到 Unicode 的自动转换。如果需要手动实现类似的转换逻辑,可以结合上述方法处理。 ```cpp CString strA("你好"); std::wstring wstr = ANSIToUnicodeStd(std::string(CT2A(strA))); // 需要包含 <atlconv.h> ``` 此类操作可用于在非 Unicode 工程中将 `CString` 内部存储的 ANSI 字符串转换为 Unicode 格式 。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值