0

The user will input a string value from the terminal. I can represent that as in integer fine. However I need to be able to convert that into a byte array / gsl::span. Is this possible?

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

int main()
{
    // integer representation
    std::string s = "0xaabbccdd";
    unsigned int x = std::stoul(s, nullptr, 16);
    std::cout << x << "\n";

    // byte array or gsl::span
    // std::array<uint8_t, 4> val{0xaa, 0xbb, 0xcc, 0xdd};
}

Update possible solution (but using std::vector)

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>

std::vector<std::string> split(const std::string & str, int len)
{
    std::vector<std::string> entries;
    for(std::string::const_iterator it(str.begin()); it != str.end();)
    {
        int num = std::min(len,(int)std::distance(it,str.end()));
        entries.push_back(std::string(it,it+num));
        it=it+num;
    };
    return entries;
}

int main() {
    std::string str{"0xaabbccdd"};
     str.erase(0, 2);
    for (auto str : split(str, 2)) {
      std::cout << str << std::endl;
    }
    return 0;
}
tester123
  • 399
  • 1
  • 3
  • 10

1 Answers1

0

C++17 and above: std::string::data() returns a mutable C-string represantation.

Older C++: You can get the bytes using std::string::data, but it is not guaranteed to be null-terminated. You can also get a null-terminated string using std::string::c_str.

Note - In older C++, the returned C-string is not guaranteed to be mutable (i.e., it returns const char *). To the best of my knowledge it is always mutable, so you can cast the constness away.

Michael
  • 932
  • 6
  • 15
  • _To the best of my knowledge it is always mutable, so you can cast the constness away._ That'll result in **Undefined Behavior**. See [documentation](https://en.cppreference.com/w/cpp/language/const_cast). Quote: "Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior." – Azeem Apr 09 '20 at 11:50
  • You would be right if the data was indeed const, but, it is not in all the implementations I know. This is also why C++17 explicitly states that `data()` is mutable. – Michael Apr 09 '20 at 12:53
  • Adding the relevant references in your answer would make it more plausible. – Azeem Apr 09 '20 at 13:03
  • https://en.cppreference.com/w/cpp/string/basic_string/data – Michael Apr 09 '20 at 14:12