2

In c, why is that ~177 yields -178, while ~0177 yields -128?

I tried printing out the values before and after, but couldn't discern anything. I also couldn't anything explaining this topic. I am reading "The C Programming Language".

Kunseok
  • 263
  • 1
  • 7

2 Answers2

3

The leading zero indicates that 0177 is an octal number (127).

ikegami
  • 367,544
  • 15
  • 269
  • 518
2

The constants 177 and 0177 are not the same value. The former is decimal which the latter is octal.

From section 6.4.4.1 of the C standard:

3 A decimal constant begins with a nonzero digit and consists of a sequence of decimal digits. An octal constant consists of the prefix 0 optionally followed by a sequence of the digits 0 through 7 only. A hexadecimal constant consists of the prefix 0x or 0X followed by a sequence of the decimal digits and the letters a (or A) through f (or F) with values 10 through 15 respectively.

4 The value of a decimal constant is computed base 10; that of an octal constant, base 8; that of a hexadecimal constant, base 16. The lexically first digit is the most significant.

The octal constant 0177 is equal to 127 in decimal. As a 32-bit hex value, it is represented as 0x0000007f. Using the ~ operator on this value gives you 0xffffff80. Assuming 2's complement representation for negative numbers, this is -128 in decimal.

dbush
  • 205,898
  • 23
  • 218
  • 273