2
int main () {
  char k = 0xd8;
  cout << hex << k << endl;
}

For some reason this prints out the character form of k and not the hex form of d8. Doing cout << hex << (int) k << endl; gives me ffffd8 which is not the one I want.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Math is Hard
  • 896
  • 1
  • 12
  • 24
  • It looks like you meant for `k` to have type `unsigned char`; `char` may be signed and thus has no guarantee of being able to store a number as large as `0xd8`. –  Sep 28 '15 at 02:34

1 Answers1

4

This is simply one of the many deficiencies in C++, and another reason why I stick with C when I can. You can read more about the topic in the references I provided below. To save yourself some hassle, consider just going with the printf() family of functions in production code, as the fix isn't guaranteed to be standards-compliant.

Code Listing


#include <iostream>
using namespace std;

int main(void)
{
    unsigned char k = 0xd8;
    cout << "k = 0x" << hex << +k << endl;
}

Sample Output


k = 0xd8

References


  1. Code critique: Stack Overflow posters can’t print the numeric value of a char, http://cpp.indi.frih.net/blog/2014/08/code-critique-stack-overflow-posters-cant-print-the-numeric-value-of-a-char/, Explicit C++, Accessed 2015-09-27
  2. Tippet: Printing numeric values for chars (and (u)int8_t), http://cpp.indi.frih.net/blog/2014/09/tippet-printing-numeric-values-for-chars-and-uint8_t/, Explicit C++, Accessed 2015-09-27
Cloud
  • 18,753
  • 15
  • 79
  • 153
  • 3
    Aside: `+k` is essentially just an esoteric way of writing `(int) k`. (or maybe `(unsigned int) k`; I don't recall that detail) –  Sep 28 '15 at 02:37
  • Also, what exactly about this do you believe isn't standards compliant? There are good reasons for using `printf` in C++, but this isn't one of them. – Ben Voigt Sep 28 '15 at 02:47
  • http://stackoverflow.com/a/25701418/103167 – Ben Voigt Sep 28 '15 at 02:57