Tuesday, April 5, 2011

set integer value as bit mask

What is simplest way to assign a bit mask to integer value? For example I want integer with first, third and forth bits = 1, other = 0.

Certainly I am looking for code, not for single value! And certainly there lot of possibilities, but I try to find simplest and most descriptive looking

From stackoverflow
  • This should do it:

    int x = 0x0D;
    

    And if you're lucky enough to use gcc and don't need to be portable:

    int x = 0b1101;
    
    Beska : Hmm. This answers the example question, but I'm guessing he wants a more general answer. (of course, that's really just a guess, since there's not any detail...)
  • Use the OR Bitwise operator (|) to combine bits:

    #define FIRST_BIT (0x1)
    #define SECOND_BIT (0x2)
    #define THIRD_BIT (0x4)
    #define FOURTH_BIT (0x8)
    /* Increase by for each bit, *2 each time, 
       0x prefix means they're specified via a hex value */
    
    int x = FIRST_BIT | THIRD_BIT | FOURTH_BIT;
    

    And you can check if a bit is set using the AND Bitwise operator (&):

    int isset = x&FIRST_BIT;
    
  • Here is an online bit converter, if you don't want to do the sum yourself:

    http://www.binaryconvert.com/convert_unsigned_int.html

    Just fill in the bits below (e.g. 1101), and compute the answer (e.g. 0x0000000D). Any capable calculator should be able to do the same ...

  • If you want your code to be readable in terms of the bit numbers, something like this may be useful:

    #define b0  0x0001
    #define b1  0x0002
    #define b2  0x0004
    #define b3  0x0008
    #define b4  0x0010
    :
    #define b15 0x8000
    
    int mask = b3|b2|b0;
    

    But, after a while you should be able to tell which hex values relate to which bits and you won't need mnemonic tricks like that:

    int mask = 0x000d;
    
    Awaken : Exactly like I would have done it. Readable and clear. For a large project, having those #defines is common, so doing the mask with the bit ORs would be my choice for clarity down in the code.
  • int something = (0x00000001) & (0x00000001 * 2) until you get to where you want.

    Stephen Canon : You want `|` (bitwise or), not `&` (bitwise and).
  • I think the best way to think (!) is to just index bits from 0, and then apply "to set the n:th bit, bitwise-OR with the value (1 << n)":

    int first_third_and_fourth = (1 << 0) | (1 << 2) | (1 << 3);
    
    Vladimir : thanks, it looks most simplest and descriptive way

0 comments:

Post a Comment