1
#include <stdio.h>
#include <stdlib.h>

int main() {
unsigned char a=100,b=50;

printf("%d & %d = %d\n",a,b,a&b);
printf("%d | %d = %d\n",a,b,a|b);
printf("%d ^ %d = %d\n",a,b,a^b);
printf(" ~%d = %d\n",a, ~a);       /*the out come of this  line would be this: ~100 = -101 */
printf(" %d >> 2= %d\n",a, a>>2);
printf(" %d << 2= %d\n",a, a<<2);
system("pause");
return 0;
}

/the out come should be 155 ,isn't it?/

3
  • Hint: 256 - 101 = ? Commented Feb 21, 2022 at 3:53
  • 1
    It's not broken, but your printf calls are. Try printf(" ~%hhu = %hhu\n", a, ~a); ... and please, you've tagged this question as C++ so stop using the C library functions. Commented Feb 21, 2022 at 3:53
  • There is no operator-keyword here. Don't tag indiscriminately. Commented Feb 22, 2022 at 0:33

2 Answers 2

6

According to the standard, the operand of ~ will undergo integral promotion. So here we will first promote a to int.

[expr.unary.op]: The operand of ~ shall have integral or unscoped enumeration type; the result is the ones' complement of its operand. Integral promotions are performed.

If int is 4 bytes (for example), the value of the promoted a is 0x00000064. The result of ~a is 0xFFFFFF9B, which is exactly -101(If using two's complement to represent integers).

Please note that although variadic arguments will undergo integral promotion, here ~a is of type int and no additional promotion is required.

Sign up to request clarification or add additional context in comments.

Comments

-2
100 = 0x64
~0x64 = 0x9B

In printf(" ~%d = %d\n",a, ~a);, the second format specifier %d expects a signed integer, so the result 0x9B will be extended to a signed integer. The MSB of 0x9B is 1, so it is regarded as a negative value.

0x9B ---extends to>>> 0xFFFFFF9B = -101

If you want the result as 155, you need a unsigned cast so the 0x9B will be extended to 0x0000009B.

#include <stdio.h>

int main() {
  unsigned char a = 100, b = 50;

  printf(" ~%d = %d\n", a, ~a);
  printf(" ~%d = %d\n", a, (unsigned char)~a);

  return 0;
}

This will give result:

gcc test.c
./a.out

 ~100 = -101
 ~100 = 155

4 Comments

you should clarify which operation caused the subtle promotion: the negation operator or the call of printf?
Your first paragraph is just utter nonsense. That's not how C or C++ works.
@SebastianRedl I didn't say they are C/C++ code. It is pseudocode for explanation, and most programmers will understand.
@ZongruZhan I'm not talking about the code snippet. I'm talking about the text below.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.