读取包含十六进制内容的 CSV 文件行并将其转换为十进制

Reading CSV file lines with hex content and convert it to decimal

这是我的 CSV 文件,它的内容是十六进制的。

a3 42 fe 9e 89 
a3 43 14 9d cd 
a3 43 1e 02 82 
a3 43 23 bd 85 
a3 43 39 d5 83 
a3 43 3e b9 8d 
a3 43 3f 44 c0 
a3 43 50 c9 49 
a3 43 67 29 c8 
a3 43 67 43 0d 

我只需要倒数第二个值,提取该值的代码就是这个。

void getvalues(){
        std::ifstream data("mydata1.CSV");
        int row_count =0;
        std::string line;

        while(std::getline(data,line))
        {
            row_count +=1;
            std::stringstream lineStream(line);
            std::string cell;
            int column_count = 0;

            while(std::getline(lineStream,cell,' '))
            {
                column_count+=1;
                if ( column_count == 5){
                  std::cout << std::dec<< cell[0]<< std::endl;
            }
        }
}

由于我正在将这些行读入字符串 cell,因此我无法进行任何转换。起初我尝试用 int 包装 cell 但它 returns 字符的 ASCII 值非常明显,我不应该那样做。

如果要将字符串转换为整数,可以使用std::stoi,它包含在字符串包中。默认情况下,您可以这样使用 stoi:

int num = std::stoi(cell)

然而,由于我们要解析一个以 16 为底的十六进制数,因此我们需要像这样使用它:

int num = std::stoi(cell, 0, 16)

关于此的快速文章:https://www.includehelp.com/stl/convert-hex-string-to-integer-using-stoi-function-in-cpp-stl.aspx