在c ++中输入十六进制字符串并将每个字节转换为十进制

时间:2015-02-12 12:53:10

标签: c++ string

我有六角形固定长度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"

2 个答案:

答案 0 :(得分:2)

所以你的问题包括5个部分:

1.切掉长度为10到5个十六进制字符串的六角形字符串,每个字符串各占两个字符 2.将生成的十六进制字符串数组转换为十进制数 3.将十进制值存储在unsigned 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&amp; 3 + 4&amp; 5),但这种方法更清洁。

希望这能解决它。

答案 1 :(得分:0)

下次,请小心你的问题,因为它不是很清楚,但我想我明白了。快乐的一天,我为你做了一个代码,但一般你必须发布你的代码,然后有人会帮助你。

#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;
}