0

I am trying to convert a string to a vector of ASCII value uint8_t

For example, if I have a string that is "500" I would want a vector that is {53, 48, 48} where these values are hex 0x35, 0x30, 0x30. This is what I am currently doing and it is not working

#include <iostream>
#include <string>
#include <vector>
int main() {
    std::string number = "500";
    std::vector<std::uint8_t> bytes;
    for (auto& c : number)
        bytes.push_back(static_cast<std::uint8_t>(c));

    for (auto& c : bytes)
        std::cout << c << std::endl;
    return 0;
}

But I just get 5, 0, 0 as output where I was expecting 53, 48, 48

user2840470
  • 919
  • 1
  • 11
  • 23
  • You haven't written any code that would convert anything to a displayable hex representation. If that's what you want, which isn't clear. –  Apr 30 '19 at 23:00
  • @NeilButterworth I was just hoping to get the integer value, I will edit the question. – user2840470 Apr 30 '19 at 23:02

1 Answers1

1

std::cout << c << std::endl; is writing std::uint8_t as a character (see this question for details). You have to cast it to an integer to actually get the result you want.

For example (wandbox link):

std::cout << static_cast<int>(c) << std::endl;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Serikov
  • 1,159
  • 8
  • 15