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

前端 未结 5 502
粉色の甜心
粉色の甜心 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:42

    I would choose BigInteger for this...

    class Test {
        public static void main(String[] args) throws Exception {
            Long value = 12L;
            BigInteger b = new BigInteger(String.valueOf(value));
            System.out.println(b.toString(2) + " " + value);
            b = b.setBit(1);
            b = b.clearBit(2);
            value = Long.valueOf(b.toString());
            System.out.println(b.toString(2) + " " + value);
        }
    }
    

    and here is the output:

    1100 12
    1010 10
    

提交回复
热议问题