用c++将十六进制字符串切碎,并将中的每个字节转换为十进制
chop hex string in c++ and convert each byte in to decimal
我有固定长度为10的十六进制字符串。
在c++中,我想把这个字符串分成5部分,把每个十六进制数转换成十进制,然后再把每个十进制数转换成字符串。
e.g. d3abcd23c9
e.g. after chopping
str1= d3
str2 = ab
str3 = cd
str4 = 23
str5= c9
convert each string in to unsigned int no:
no1 = 211
no2= 171
no3= 205
no4= 35
no5= 201
again convert each of this number in to str:
dstr1 = "211"
dstr2 = "171"
dstr3 = "205"
dstr4 = "35"
dstr5 = "201"
所以你的问题由5部分组成:
1.剪掉一个长度为10到5个的十六进制字符串,每个字符串包含2个字符
2.将得到的十六进制字符串数组转换为十进制
3.将十进制值存储在无符号int数组中。
4.将无符号整数数组转换为字符串
5.将生成的字符串保存到字符串数组中
#include <iostream>
using namespace std;
int main() {
string hexstr = "d3abcd23c9"; //your hex
string str[5]; //To store the chopped off HEX string into 5 pieces
unsigned int no[5]; //To store the converted string array (HEX to DEC)
string dstr[5]; //Stores the results of converting unsigned int to string
int x=0; //
for (int i=0; i < 5; i++) // Fixed length 10 in chunks of 2 => 10/2 = 5
{
str[i] = hexstr.substr(x, 2); //Part 1
x += 2; //Part 1
no[i] = std::strtoul(str[i].c_str(), NULL, 16); //Part 2 & 3
dstr[i] = std::to_string(no[i]); //Part 4 & 5
cout << dstr[i] << endl; //Just for you to see the result
}
return 0;
}
您可以连续地将部分划分为单独的for循环(1+2&3+4&5),但这种方法更干净
希望这能解决问题。
下次,小心你的问题,因为它不是很清楚,但我想我理解了。祝你愉快,我为你做了一个代码,但一般来说你必须发布你的代码,然后有人会帮你
#include <vector>
#include <string>
#include <cstring>
#include <iostream>
#include <sstream>
static unsigned int hex2dec(const std::string& val)
{
unsigned int x;
std::stringstream ss;
ss << std::hex << val;
ss >> x;
return x;
}
static std::vector<unsigned int> chopperHexStringToDec(const std::string& str, int splitLength = 2)
{
std::vector<unsigned int> data;
std::size_t parts = str.length() / splitLength;
for (std::size_t i = 0; i < parts; ++i)
data.push_back(hex2dec(str.substr(i * splitLength, splitLength)));
if (str.length() % splitLength != 0)
data.push_back(hex2dec(str.substr(splitLength * parts)));
return data;
}
int main(int ac, const char **av)
{
if (ac != 2 || std::strlen(av[1]) != 10)
return 1;
std::vector<unsigned int> data = chopperHexStringToDec(av[1]);
std::vector<unsigned int>::iterator it = data.begin();
std::vector<unsigned int>::iterator it_end = data.end();
while (it != it_end)
{
std::cout << *it << std::endl;
++it;
}
return 0;
}
相关文章:
- 如何在连接器 C++ 中将原始字节转换为字符串
- 将 char[] 数组转换为字节,然后将字节转换为 int,反之亦然
- 如何在 c++ 中将字节转换为 ASCII 十六进制表示形式?
- OPENSSL 将二进制字节转换为 SHA256 C++
- 如何将音频字节转换为样本
- C++ 如何将 char[] 中的多个字节转换为一个整数
- 删除字节转换的char*
- 如何将二进制字节转换为可打印的数值
- 将 MFRC522 UID 十六进制字节转换为可打印的小数
- 用c++将十六进制字符串切碎,并将中的每个字节转换为十进制
- Qt是否有一种将字节转换为int的方法,反之亦然
- UCS-4 到 Solaris 上的多字节转换
- 使用 C++ 将四个字节转换为整数
- 将字节转换为无符号整数的最快方法
- 如何在mac上将多字节转换为宽字符
- 将字节转换为整数
- 在Arduino错误时将4个字节转换为长字节
- 更正从C++到delphi AnsiString的字节转换
- 用C++将4个字节转换为3个字节
- 正在将字节转换为char数组,然后再转换回来