What is - (- 128) for a signed single char byte in C?

My little program:

#include <stdio.h> int main() { signed char c = -128; c = -c; printf("%d", c); return 0; } 

Print

 -128 

Does the minus (-) operator carry over the CPU?

+6
source share
3 answers

The unary minus operand first undergoes standard promises, so it is of type int , which can represent the value -128 . The result of the operation is a value of 128 , also of type int . The conversion from int to signed char , which is the narrowing of signed types, is determined by the implementation.

(Your implementation seems to do a simple migration: 125, 126, 127, -128, -127, ...)

+9
source

Note: -128 in 2 supplements is 1000 0000 (in one byte), and 128 also 1000 0000 . If you execute char c = 128 and print it, it will be -128 for the following reason:

The value of A char variable = 128 is stored in memory as follows.

 MSB +----+----+----+---+---+---+---+---+ | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +----+----+----+---+---+---+---+---+ 7 6 5 4 3 2 1 0 

Now,

  • this value will be interpreted as a negative value, since MSB 1 ,
  • to print the value of this addition -ve number 2, that is, also 128 in one byte, therefore the output: -128

    2 addition:

      1000 0000 0111 1111 1 complement + 0000 0001 ----------- 1000 0000 2 complement Magnitude = 128 So in one byte 128 == -128 
+4
source

because the byte (char) cannot contain 128

 -128 = 0x80 

what neg does, converse and plus 1

 -(-128) = (~0x80) + 1 = 0x7F + 1 = 0x80 

Daha, you got 0x80 again

+1
source

Source: https://habr.com/ru/post/948709/


All Articles