Martin Dzhonov
Martin Dzhonov

Reputation: 1081

A way to invert the binary value of a integer variable

I have this integer int nine = 9; which in binary is 1001. Is there an easy way to invert it so I can get 0110 ?

Upvotes: 34

Views: 45928

Answers (6)

Kuba
Kuba

Reputation: 3056

1) Create a mask for the last n bits that you want to flip

mask = (1<<n) - 1

2) use xor

a ^ mask

Additionally if you want to flip bits starting from the first 1 in binary representation you can do this

n = 0; while ((1<<n) <= a) n++;

Upvotes: 0

Bas
Bas

Reputation: 27105

If we consider 9 as an integer like this:

00000000000000000000000000001001

and you want to have:

00000000000000000000000000000110

instead of:

11111111111111111111111111110110

And do care about more than the last nibble (e.g. also want to handle 128903).

Then you can create a mask and apply it:

uint value = 9; //or try 1290320
uint mask = 0;
for (int i = 1; i <= 16; i *= 2)
     mask |= mask >> i;
value = mask & (~value);

You could speed this up using a modified version of http://en.wikipedia.org/wiki/Find_first_set, or using the bsf asm instruction.

Upvotes: 3

Mark Ransom
Mark Ransom

Reputation: 308206

This problem is not completely specified - do you only care about 4 bits, or should the answer adjust to the number of significant bits in the input? If it's the latter then you'll need some sophisticated bit manipulation to mask off the upper bits.

I'll slightly modify a Bit Twiddling Hack to create the mask.

int mask = num;
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
mask |= mask >> 8;
mask |= mask >> 16;
int inverse = ~num & mask;

See it in action: http://ideone.com/pEqwwM

Upvotes: 4

sh1ng
sh1ng

Reputation: 2973

Use xor with 111111....

var inverted = a ^ int.MinValue

Upvotes: 1

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

int notnine = ~nine;

If you're worried about only the last byte:

int notnine = ~nine & 0x000000FF;

And if you're only interested in the last nibble:

int notnine = ~nine & 0x0000000F;

The ~ operator is the bitwise negation, while the mask gives you only the byte/nibble you care about.

If you truly are interested in only the last nibble, the most simple is:

int notnine = 15 - nine;

Works for every nibble. :-)

Upvotes: 49

Servy
Servy

Reputation: 203824

There's an operator specifically for it, ~.

nine = ~nine;

Upvotes: 18

Related Questions