用c++将十六进制字符串切碎,并将中的每个字节转换为十进制

chop hex string in c++ and convert each byte in to decimal

本文关键字:字节 转换 十进制 十六进制 c++ 字符串      更新时间:2023-10-16

我有固定长度为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;
}