Search code examples
c++vectorhexunsigned-char

Storing hexadecimal representation of int at std::vector of unsigned char


In this code:

  vector<unsigned char> result;
  int n;
  unsigned char c;

  c = (n >> 24) & 0xFF;
  result.push_back(c);
  c = (n >> 16) & 0xFF;
  result.push_back(c);
  c = (n >> 8) & 0xFF;
  result.push_back(c);
  c = n & 0xFF;
  result.push_back(c);

I want, instead of add one single byte to the vector (c), add each digit of the hexadecimal representation of the integer n (like FF for something like 0xFF).

Anyone can give a hint of how to accomplish that?

update

I update my code to this, which works with most values except 0 and 1 (the hexadecimal representation stays with one digit and one space: "0 " and "1 ").

  BYTE c;

  vector<BYTE> v_version;
  c = (version >> 24) & 0xFF;
  v_version.push_back(c);
  c = (version >> 16) & 0xFF;
  v_version.push_back(c);
  c = (version >> 8) & 0xFF;
  v_version.push_back(c);
  c = version & 0xFF;
  v_version.push_back(c);

  for (auto c: v_version)
  {
    ostringstream oss;
    oss << hex << static_cast<int>(c);
    result.push_back( oss.str()[0] );
    result.push_back( oss.str()[1] );
  }

Solution

  • n is uninitialized so first take care of that.

    Depending on what your ultimately goal is the best solution is not to store the hex digits, but to keep the current binary representation and just print in hex. To do that you need std::hex and an integer cast:

    std::cout << std::hex << std::setw(2) << std::setfill('0');
    std::cout << static_cast<unsigned>(c);
    

    If you want to store the result instead of printing it you can do it with ostringstream like in your example. But I strongly suggest std::string or std::vector<char>. Despite its name unsigned char should not be used with characters. If you have characters like here the underlying type should be char.

    • use char for characters
    • use unsigned char for raw memory (byte)
    • don't use signed char