Koushik
Koushik

Reputation: 53

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

Here is my CSV file and its contents are in hex.

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 

I need only the second-last value and the code to extract that value is this.

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

Since I am reading the lines into a string cell, I am unable to do any conversion. At first I tried wrapping the cell with an int but it returns me the ASCII value of the character which is quite obvious and I shouldn't have done that.

Upvotes: 0

Views: 207

Answers (1)

Ryan Kane
Ryan Kane

Reputation: 306

If you want to convert a string to an integer, you can use std::stoi, which is included in the string package. By default, you can use stoi as such:

int num = std::stoi(cell)

However since we want to parse a base 16 hex number, then we need to use it like:

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

Quick article about this: https://www.includehelp.com/stl/convert-hex-string-to-integer-using-stoi-function-in-cpp-stl.aspx

Upvotes: 1

Related Questions