How to set/unset a bit at specific position of a long?

前端 未结 5 501
粉色の甜心
粉色の甜心 2020-12-24 03:35

How to set/unset a bit at specific position of a long in Java ?

For example,

long l = 0b001100L ; // bit representation

I want to s

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 03:46

    The least significant bit (lsb) is usually referred to as bit 0, so your 'position 2' is really 'bit 1'.

    long x = 0b001100;  // x now = 0b001100
    x |= (1<<1);        // x now = 0b001110 (bit 1 set)
    x &= ~(1<<2);       // x now = 0b001010 (bit 2 cleared)
    

提交回复
热议问题