0

Going through K&R C programming book's Excercise2.1. I tried looking it up but the explanations were a little high level. So what is "~". why does printf("%u", (unsigned char)~0); print out 255 and printf("%u\n", ~0); prints 4294967295.

Thank you :)

Lax
  • 55
  • 5
  • thanks. that makes sense. a "tilde" is a bitwise NOT operator but what does `(unsigned char)~0` mean? thanks again – Lax Mar 28 '23 at 03:50
  • 1
    An `unsigned char` is an 8-bit unsigned integer (so, a number in the range 0-255). Without that cast, `~0` is a native integer. On a system where that is 32 bits, you get `4294967295`. – larsks Mar 28 '23 at 03:54
  • did some googling. `unsigned-char` can go anywhere from 0 to 255. a NOT operator on it just flips all the value so its displayes highest unsigned char that is 255. and binary representation of `~0` in 32 which is 4294967295 in decimal – Lax Mar 28 '23 at 03:57
  • 2
    That is...exactly what I said. – larsks Mar 28 '23 at 11:50

2 Answers2

3

What does tilde(~) operator do?

TL;DR It's a bitwise not, meaning all the bits are flipped.

For your first example, the ~ operator inverts all 32 bits in the integer 0 (stored as 4 00000000 bytes), transforming it into all ones (four 11111111 bytes). Then it is cast to an unsigned char, truncating it to just one 11111111 byte. In decimal, 11111111 is 255. For your second example, the four 11111111 bytes resulting from ~0 is interpreted as an unsigned int, which equals 4294967295 in decimal.

Noah Wiggin
  • 365
  • 1
  • 6
  • 2
    Prefix `0x` means "Hex" values, and 0x1111 in hex is `0001 0001 0001 0001` in binary. I think you meant to write `0b11111111`, because the `0b` prefix means "Binary" – abelenky Mar 28 '23 at 15:05
2

First you should know '~' character is bit-wise NOT

let's see what will happen when we use bit-wise not

unsigned char var = ~0;

printf("%u", var); // Output: 255

in binary format

# 8-Bit Variable

0b00000000 -> 0b11111111
OR
0b11111111 -> 0b00000000

or another example

0b11001100 -> 0b00110011

so we learn that bit-wise NOT reverse every bit in our variable, no matter what bit is 0 or 1 it'll be reverse

now what will happen if we use bit-wise NOT over a larger variable

unsigned short var = ~0;

printf("%X", var); // Output: FFFF

in binary:

0b00000000_00000000 -> 0b11111111_11111111

so now you can sure bit-wise NOT don't care about value of variable and size of variable, it just reverse all bits in our variable even if you have a 64-bit variable

Ali Mirghasemi
  • 462
  • 2
  • 7