将中文转换为二进制主要有以下两种方法,具体实现方式因编码标准不同而有所差异:
一、基于字符编码转换
UTF-8编码(推荐) - 每个汉字通常占用3个字节,适用于国际化场景。 - 示例代码(Python):
```python
s = "中国"
binary_data = s.encode('utf-8')
print(binary_data) 输出: b'xe4xbdxa0xe5xa5xbd'
```
- 转换为十六进制:`s.encode('utf-8').hex()`。
GB2312编码
- 早期中文编码标准,每个汉字占用2个字节。 - 示例代码(C++):
```cpp
include include include std::string strToBinary(const std::string& str) { std::string binary; for (char c : str) { binary += std::hex << (int)c; } return binary; } int main() { std::string s = "中国"; std::string binary = strToBinary(s); std::cout << binary << std::endl; // 输出: 4e2d 502d return 0; } ``` 二、二进制位级转换 逐位转换: 将每个字符的ASCII或Unicode码转换为二进制数,再按位拼接。 示例(Python): ```python s = "中国" binary_str = ''.join(format(ord(c), '08b') for c in s) print(binary_str) 输出: 11000010 10000001 10000000 10000001 ``` 注意事项 编码选择