Search code examples
c++stringstringstream

c++ stringstream read doesn't seem to read the whole buffer


I have the following code: https://godbolt.org/z/9aqqe5eYh

#include<string>
#include<sstream>
#include<iomanip>
#include<iostream>

int main() {
  std::string line = "fa0834dd";

  for(int i = 0; i < line.length(); i += 2) {
    std::stringstream ss;
    std::uint8_t byte;

    ss << std::hex << line.substr(i, 2);
    std::cout << ss.str() << " ";
    ss >> byte;
    std::cout << std::hex << std::setw(2) << byte << std::endl;
  }
}

Ideally, this takes in a string of hex numbers, splits them into bytes (pair of hex digits) and stores it into bytes (for illustrative purposes, I use only one std::uint8_t above). The above code outputs this:

Program returned: 0
Program stdout
fa  f
08  0
34  3
dd  d

Which seems kinda odd. An std::uint8_t should be enough to store 2 hex character's worth of data. But it seems like ss >> byte only stores the front hex character. My guess is that:

ss << std::hex << line.substr(i, 2);

actually stores each hex character as 1 byte?

How would I fix the above code to generate an single-byte value equal to 2 hex characters in the string?


Solution

  • stringstream is not eligible for parsing the character representation into a value in byte.

    You may use something lik strtol to actually parse the string into value.

    #include<string>
    #include<sstream>
    #include<iomanip>
    #include<iostream>
    #include<cstdint>
    
    int main() {
      std::string line = "fa0834dd";
    
      for(int i = 0; i < line.length(); i += 2) {
        std::string ss = line.substr(i,2);
        
        std::cout << ss << " ";
    
        std::uint8_t byte = static_cast<std::uint8_t>(strtol(ss.c_str(), NULL, 16));
        std::cout << std::hex << static_cast<int>(byte) << std::endl;
      }
    }
    

    Ref post