Pero
Pero

Reputation: 29

How to compute expressions like ~0x000C by hand?

I'm student of electrical engineering. At our programming class we were given bunch of exercises for C language and asked to explain what happens and how your IDE performs bit operations.

So, for example if I'm given unsigned short x = 0x000C and perform ~x, the output is 65523. How does your IDE perform this operation?

Upvotes: 0

Views: 230

Answers (1)

Luke Hollenback
Luke Hollenback

Reputation: 791

To provide some context, generally speaking, we use the following prefixes to denote different base representations of numbers:

  • No prefix means base-10, a.k.a. decimal (what we use in everyday life)
  • 0x means base-16, a.k.a. hexadecimal (count from 0-9A-F, so a single digit can represent any value between 0 and 15...this requires four bits because the number 15 has a decimal representation of 0b1111)
  • 0b means base-2, a.k.a. binary (count from 0-1...requires 1 bit per digit)
  • 0 means base-8, a.k.a. octal (count from 0-7...requires 3 bits per digit)

So, given that, which you likely already knew but another user may not, this is what is happening behind the scenes in a very high-level way. Assuming an unsigned short is 16 bits wide in your environment, and given...

unsigned short x = 0x000C = 0b0000 0000 0000 1100

...a ~ is a bitwise negation operator, which means you just flip all the bits. So, for example:

~0b0000 0000 0000 1100 = 0b1111 1111 1111 0011 = 0xFFF3 = 65523

As a note, things like this get tricky when you start trying to do them in languages (like Python and VBScript) that abstract native types like integers into "infinitely large numbers". Flipping the bits of a 16-bit unsigned short is a lot different, and more possible, than flipping the bits of an "infinitely large number".

Upvotes: 6

Related Questions