Set specific bit in byte

前端 未结 5 512
故里飘歌
故里飘歌 2020-11-30 19:29

I\'m trying to set bits in Java byte variable. It does provide propper methods like .setBit(i). Does anybody know how I can realize this?

I can iterate

相关标签:
5条回答
  • 2020-11-30 19:32

    The technique you need is to isolate the chosen bit and either set or clear it. You already have the expression to isolate the bit since you're using that to test it above. You can set the bit by ORing it in, or clear the bit by bitwise AND with the 1's complement of the bit.

    boolean setBit;
    my_byte = setBit
              ? myByte | (1 << i)
              : myByte & ~(1 << i);
    
    0 讨论(0)
  • 2020-11-30 19:34

    To set a bit:

    myByte |= 1 << bit;
    

    To clear it:

    myByte &= ~(1 << bit);
    
    0 讨论(0)
  • 2020-11-30 19:35

    Just to complement Jon‘s answer and driis‘ answer

    To toggle (invert) a bit

        myByte ^= 1 << bit;
    
    0 讨论(0)
  • 2020-11-30 19:47

    Use the bitwise OR (|) and AND (&) operators. To set a bit, namely turn the bit at pos to 1:

    my_byte = my_byte | (1 << pos);   // longer version, or
    my_byte |= 1 << pos;              // shorthand
    

    To un-set a bit, or turn it to 0:

    my_byte = my_byte & ~(1 << pos);  // longer version, or
    my_byte &= ~(1 << pos);           // shorthand
    

    For examples, see Advanced Java/Bitwise Operators

    0 讨论(0)
  • 2020-11-30 19:52

    Please see the class java.util.BitSet that do the job for you.

    To set : myByte.set(bit); To reset : myByte.clear(bit); To fill with a bool : myByte.set(bit, b); To get the bool : b = myByte.get(bit); Get the bitmap : byte bitMap = myByte.toByteArray()[0];

    0 讨论(0)
提交回复
热议问题