A way to invert the binary value of a integer variable

后端 未结 6 535
忘掉有多难
忘掉有多难 2020-12-10 10:44

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 ?

相关标签:
6条回答
  • 2020-12-10 11:17

    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.

    0 讨论(0)
  • 2020-12-10 11:18

    Use xor with 111111....

    var inverted = a ^ int.MinValue
    
    0 讨论(0)
  • 2020-12-10 11:23
    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. :-)

    0 讨论(0)
  • 2020-12-10 11:25

    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

    0 讨论(0)
  • 2020-12-10 11:33

    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++;
    
    0 讨论(0)
  • 2020-12-10 11:36

    There's an operator specifically for it, ~.

    nine = ~nine;
    
    0 讨论(0)
提交回复
热议问题