Thursday, October 4, 2007

Default C/C++ char is signed

Programmer often forgot that the default char type is signed, instead of unsigned. In VC, /J gives the char unsigned. We ran into a problem this week:

if ( character > 126 character < 32) {
sprintf(sTemp, "%02X", character);
os << '#' <<>

In VC 2003, sTemp gives "FFFFFFFFFac" for character 0xac. To correct the issue, convert it to unsigned integer type, such as
sprintf(sTemp, "%02X", (unsigned char)character );

Note that this statement

if ( character > 126 character <>

implies that the character is unsigned type. This variable should be declared as unsigned char at the beginning.

No comments: