0
int main(){
    char c=0371;
    cout<<hex<<(int) c;
 return 0;
}

I converted c into binary system(011 111 001) then hexadecimal (f9). Then why does it give the result fffffff9 not f9?

Lucy
  • 19
  • 2
  • 2
    Your 8-bit `char` is **signed** and is being **sign-extended** to a 32-bit **signed** `int` before it is output to the console. Since its initial value has its high bit set to 1, so do the extra bits – Remy Lebeau Oct 30 '17 at 17:32
  • The cast to int is sign extending. – Steve Oct 30 '17 at 17:33
  • 1
    `char` may or may not be signed. `0371` will not fit in an `signed char`. See https://stackoverflow.com/questions/2054939/is-char-signed-or-unsigned-by-default – François Andrieux Oct 30 '17 at 17:33
  • @vsoftco: Yes, that leading zero is a common issue. :-( – Thomas Matthews Oct 30 '17 at 17:34
  • 3
    You are using an octal literal for some reason, its value is 11111001. A negative value, it gets sign-extended to 1111....11111001. Which is ffffff9 in hex. Maybe you didn't really intend to use octal. – Hans Passant Oct 30 '17 at 17:34
  • 1
    @FrançoisAndrieux: `0371` is not the same as `0x371`, – Remy Lebeau Oct 30 '17 at 17:34

1 Answers1

4

If the char type on your system is signed, the value 0xf9 is a negative number (specifically, it’s -7). As a result, when you convert it to an integer, it gives the integer the numeric value -7, which has hexadecimal representation 0xFFFFFFF9 (if you’re using signed 32-bit integer representations).

If you explicitly make your character value an unsigned char, then C++ will cast it as though it has the positive value 249, which has equivalent integer value 249 with hexadecimal representation 0x000000F9.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065