-3

First of all, yes I know about FAQ Converting. But I don't need that kind of type-conversion (I hope!). We have:

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

struct My_Data{
  uint16_t data;
};

using namespace std;

int main()
{
  My_Data data{ 0x12 }; // data = 0x0012
  stringstream ss;
  ss << std::hex << static_cast<int>(data.data);
  string str_data{ ss.str() };
  cout << str_data;  // It will print 12, but I want 0012

  return 0;
}

My solution was std::bitset, I just wondering if there is another solution too. because the main data type in the project is std::vector<uint8_t>, so is there any possible short way to get 0012 with std::vecotr<uint8_t>? Thanks a lot.

2 Answers2

0

The easiest method to make a std::vector<std::uint8_t> from an std::uint16_t in hex representation with width 4 and zero padded would be something like so

#include <sstream>
#include <string>
#include <iomanip>
#include <vector>
#include <cstdint>

std::vector<std::uint8_t> make_hex_vector(std::uint16_t val)
{
    std::stringstream ss;
    ss << std::setw(4) << std::setfill('0') << std::hex << val;
    auto str = ss.str();
    std::vector<std::uint8_t> ret(str.begin(), str.end());
    return ret;
}
Mestkon
  • 3,532
  • 7
  • 18
0

You don't need a stringstream to do this. There are stream manipulators that do all the adjustments you're looking for.

#include <iostream>
#include <iomanip>
#include <cstdint>

int main() {
    std::uint16_t data = 0x12;
    std::cout
        << std::setw(6) // set output field width to 6
        << std::hex // write output as hexadecimal value
        << std::setfill('0') // pad with zeros
        << std::showbase // show the prefix for the base (0x)
        << std::internal // insert the padding between the prefix and the value
        << data
        << '\n';
    return 0;
}

If you don't want the "0x", remove std::showbase and change the field width to 4.

To answer the question in the last sentence, just use the same manipulators to write out the value of each uint8_t in the vector.

If, as one of the answers assumes, you're looking for putting the characters into a std::string, that's where you'd use a std::stringstream instead of std::cout.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165