wlsk888 2023-02-19 18:06 采纳率: 90.9%

# 如何获取一个hex字符串的字符数？

ansi字节数：658
.。。。。。。。

``````    string aaa = Release("01010600", "123.456.789.188", "123.234.456.123");
printb(aaa);
printb(aaa.length());
输出：
0101060064210000000000003139322E3136382E33312E3138383139322E3136382E33312E3138383139322E3136382E33312E313139322E3136382E33312E31F0DEF1DFF5E900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000638253633501073D0701F0DEF1DFF5E932043139322E3136382E33312E31383836043139322E3136382E33312E313C084D53465420352E30FF
146
``````
• 写回答

#### 1条回答默认 最新

• CodeBytes 2023-02-19 18:44
关注

该回答引用ChatGPT

从你的输出来看，你得到的字符串是16进制格式的，每两个字符对应一个16进制数字，所以长度为146表示字符串包含了292个16进制数字（146 / 2 = 292）。

如果你想要得到字符数，那么需要将16进制转换成对应的字符，并计算字符数。具体可以使用C++的字符串流和iomanip库来实现。示例代码如下：

``````
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

int main()
{
string hexStr = "0101060064210000000000003139322E3136382E33312E3138383139322E3136382E33312E3138383139322E3136382E33312E313139322E3136382E33312E31F0DEF1DFF5E900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000638253633501073D0701F0DEF1DFF5E932043139322E3136382E33312E31383836043139322E3136382E33312E313C084D53465420352E30FF";

stringstream ss;
for (size_t i = 0; i < hexStr.length(); i += 2) {
string subStr = hexStr.substr(i, 2);
int hexNum;
sscanf(subStr.c_str(), "%x", &hexNum);
ss << (char)hexNum;
}
string charStr = ss.str();

cout << "Hex string: " << hexStr << endl;
cout << "Character string: " << charStr << endl;
cout << "Number of characters: " << charStr.length() << endl;

return 0;
}

``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

• 系统已结题 2月27日
• 已采纳回答 2月19日
• 修改了问题 2月19日
• 创建了问题 2月19日

#### 悬赏问题

• ¥15 企业资源规划ERP沙盘模拟
• ¥15 树莓派控制机械臂传输命令报错，显示摄像头不存在
• ¥15 前端echarts坐标轴问题
• ¥15 CMFCPropertyPage