c - Printing inverse of a character -
this question has answer here:
- printing hexadecimal characters in c 7 answers
i know why printf statement displays character value 4 byte value (fffffffe) in following code. since character of 1 byte, thought should getting result of fe 1 byte value.
int main(void) { unsigned char a4=1; char b4=1; printf("inverted a4 = %x\t b4= %x\n",~a4, ~b4); return(0); }
when any arithmetic or bit operation on char quantity, silently converted int first. called integer promotion. affects short (and signed char, unsigned char, , unsigned short) well. (technically, if sizeof(unsigned short) == sizeof(unsigned int) unsigned short promote unsigned int rather int, you're not trip on system characteristic anymore, though it's still allowed c standard.)
this also happens char , short when passed through anonymous arguments printf (or other variadic function).
so, code
unsigned char a4=1; char b4=1; printf("inverted a4 = %x\t b4= %x\n",~a4, ~b4); is equivalent to
... printf("inverted a4 = %x\t b4= %x\n", (int) ~(int)a4, (int) ~(int)b4); (the cast after ~ doesn't have written anyway emphasize conversion happen both because of arithmetic , because of argument passing.)
there no way turn behavior off. effect wanted, write
static_assert(char_bit == 8); printf("inverted a4 = %02x\tb4 = %02x\n", (~(unsigned int)a4) & 0xffu, (~(unsigned int)b4) & 0xffu); the difference between , code suggested mikecat , nick bit operations done on unsigned quantities. bit operations have undefined behavior when applied signed quantities, , can never remember rules are, avoid doing of them signed quantities. (the change %x %02x aesthetics.)
systems on static_assert fails vanishingly rare nowadays, again, still allowed c standard. include document program's expectations. (the 0xffu masks , %02x formatters wrong on system different value char_bit.)
Comments
Post a Comment