Unsigned char and char?

Started by
9 comments, last by ice88873 22 years, 1 month ago
YES, there''s a HUGE difference. I recently ran through some parsing code for MIDI files, and had this logic:
  void parse (const char *rawData, int dataLen){  //...  switch (*rawData & 0xF0) // switch on the status type  {    case 0x80: func1 (); break;    case 0x90: func2 (); break;    // etc.    default: throw runtime_error ("No status byte!");  }}  

Guess what? None of those switches ever worked, it threw every time even when I was specifically looking at *rawData and it was equal to 0x92 or something. In order for this to work, the switch statement has to be:
switch ((unsigned char) (*rawData & 0xF0))

Strings are signed characters by default in MSVC, and I believe it''s left up to the implementation to decide what types their strings are. In other words, if you try to do this in MSVC:
unsigned char *str = "Hello world";
..you''ll get a conversion error. So you can''t "just use unsigned everywhere", because some things are singed by default.

The main difference between signed and unsigned comes with bitshifting. If you bitshift right on a char and the high bit is set, it will sign-extend if it''s a signed character, and will not if it''s unsigned.

So yes, there''s a huge difference between signed and unsigned characters.

This topic is closed to new replies.

Advertisement