-1

I am learning about masking techniques in C. Here is a practice problem I am working on: Need to find the complement of 0x87654321 while leaving the least significant byte intact which should look like this 0x789ABC21

The only mask I'm familiar with right now is using x & 0xFF to strip all but the last byte. I don't know which bitwise operator to use to get the complement of a hex number. How do I approach that?

My book doesn't explain what a one complement of a hex number is but I googled that and found out the shortcut method to determine a one complement is to take 15 - hexDigit = complement Please correct me if I'm wrong.

ixbo45
  • 313
  • 1
  • 2
  • 7
  • 3
    `0x87654321U ^ 0xFFFFFF00U` – Kaz Sep 27 '16 at 23:35
  • Why does this produce the complement though? – ixbo45 Sep 28 '16 at 01:20
  • Because XOR is the Boolean "not equal" function. When we XOR some value X against a Boolean 1/True (X XOR True) we are saying "X not equal to True", which is the same as "X not True" which is just "not X", which is complement. The C ^ operator applies the Boolean XOR function in parallel across all the corresponding bits of the operands. So we can use a *mask* like 0xFFFFFF00 to pick which bits we want to complement. XOR-ing with 0 does nothing; X XOR 0 is X. XOR-ing with 1 flips 1 to 0 and 0 to 1.. – Kaz Sep 28 '16 at 02:08

1 Answers1

1

The bitwise complement operator in C is the tilde ~. This flips every bit in a bit pattern.

The bitwise XOR operator (^) can also be used to do a bitwise complement. The bitwise XOR truth table is below:

^| 0 1
------
0| 0 1
1| 1 0

Notice in particular that 1^0 = 1 and that 1^1 = 0. Thus, bitwise XOR with a one will also have the effect of flipping bits.

Thus, bitwise XOR with 0xFFFFFF00 will flip all but the last eight bits of a number.

David
  • 1,624
  • 11
  • 13