Barshan Das
Barshan Das

Reputation: 3767

Why TCHAR value changes if Multi-Byte Character Set used?

Here is my code:

int main()
{
    TCHAR x = 0x80;
    printf("%X", x);
    return 0;
}

If I use "Character Set = Use Multi-Byte Character Set" in Visual Studio project settings, I get output:

FFFFFF80

The same code if built with "Character Set = Use Unicode Character Set", it gives correct output:

80

Why is this different behavior?

Upvotes: 0

Views: 501

Answers (1)

Jeaninez - MSFT
Jeaninez - MSFT

Reputation: 4040

For multibyte character set : TCHAR stands for char . In the Microsoft compiler, char is an 8-bit type.

For Unicode character set: TCHAR stands for wchar_t .In the Microsoft compiler, wchar_t represents a 16-bit wide character

You are seeing the "FFFFFF" because char is signed on your system. In C, functions such as printf will promote all integers smaller than int to int. Since char is an integer , your chars are being promoted to int via sign-extension.

Since "80" have a leading 1-bit , they are being sign-extended.

I suggest you could try to use the following code to mask out the upper bits and keep only the lower 8 bits that you want.

    printf("%X", x & 0xFF);

Upvotes: 1

Related Questions