0

I need to print the exact hex value of a char variable using C++.

Here is my code:

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

int main()
{
    char val = 0xfe;

    std::stringstream ss1;
    std::stringstream ss2;

    ss1 << "#645" << std::setfill('0') << std::setw(2) << std::hex <<  val;
    ss2 << "#645" << std::setfill('0') << std::setw(2) << std::hex << (int) val;

    std::cout << ss1.str() << std::endl;
    std::cout << ss2.str() << std::endl;
}

And my output:

#6450�
#645fffffffe

And what I expected:

#645FE
Zong
  • 6,160
  • 5
  • 32
  • 46
Mendes
  • 17,489
  • 35
  • 150
  • 263
  • There are some solutions to the same question here: http://stackoverflow.com/questions/673240/how-do-i-print-an-unsigned-char-as-hex-in-c-using-ostream – Maria Dec 09 '15 at 13:03
  • It´s where I got the first code from, but it works for `unsigned char` as pointed by sergej, not for `char`.... – Mendes Dec 09 '15 at 13:07

2 Answers2

1

quick fix:

unsigned char val = 0xfe;
...
ss2 << "#645" << std::setfill('0') << std::setw(2) << std::hex << std::uppercase << 
        (int) val;

or (as proposed by @Kerrek SB):

ss2 << "#645" << std::setfill('0') << std::setw(2) << std::hex << std::uppercase <<
        static_cast<unsigned int>(static_cast<unsigned char>(val));

Note that if (on your platform) char defaults to signed char, then 0xfe is a negative number (-2).

In other words, if char is a signed char and sizeof(int) is 4, then (int)val is 0xfffffffe. That is what you get.

  • -2 as signed char: 0xfe
  • -2 as int: 0xfffffffe
sergej
  • 17,147
  • 6
  • 52
  • 89
1

I wouldn't bother with streams manipulators when it's easier to do it yourself (exploiting the implicit conversion to unsigned char).

std::string hexb(unsigned char b) {
    const char *s="0123456789ABCDEF";
    return std::string(s[b>>4]) + s[b&0xf];
}

Usage:

std::cout<<hexb(val);
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299