Defined behavior by passing the printf character ("% 02X"

I recently came across this question where the OP was having trouble printing the hex value of a variable. I believe that the problem can be summarized with the following code :

#include <stdio.h>

int main() {
    char signedChar = 0xf0;

    printf("Signed\n");
    printf("Raw: %02X\n", signedChar);
    printf("Masked: %02X\n", signedChar &0xff);
    printf("Cast: %02X\n", (unsigned char)signedChar);

    return 0;
}

This gives the following result:

Signed
Raw: FFFFFFF0
Masked: F0
Cast: F0

The format string used for each of the prints is %02XIve always interpreted as "print supplied intas a hexadecimal value with at least two digits.

The first case passes signedCharacter as a parameter and outputs an invalid value (because the other three bytes inthave all set bits).

, (0xFF) , , , char. ? : signedChar == signedChar & 0xFF?

, unsigned char (, , ?).

, - , ? /?

+5
1

, c. , . , .

printf("Raw: %02X\n", signedChar);

(char)0xf0, (char)-16, (int)-16, 0xfffffff0.

printf("Masked: %02X\n", signedChar &0xff);

0xff int, & signedChar (int)-16. ((int)-16) & ((int)0xff) == (int)0x000000f0.

printf("Cast: %02X\n", (unsigned char)signedChar);

(unsigned char)0xf0, (unsigned char)240, (unsigned int)240 hex it 0x000000f0

+10

All Articles