문제

Having the number 5 as b101, how can I change any bit of it from a certain position? Ex: change(3) will make it b100.

도움이 되었습니까?

해결책

If x contains your number and n is the binary digit that you chant to change,

public int change(int x, int n) {
    return x ^ (1 << n);
}

다른 팁

This is kind of backwards. First off, bits are usually counted starting with 0. They are also counted right-to-left.

So

Number: 1101101
Bit #:  6543210

Starting with b101, changing "bit 3" will change to b1101, you count from the right.

Changing bit 2 will change to b001.

If it is a simple integer, you can use the xor (^) operator, and shift-left (<<). For example. 5 ^ (1 << 2) is equal to 1.

More generally number ^ (1 << bitNum). will give you the value of number with the bit bitNum reversed.

Now, if you really want to start from the left, you can use Integer.highestOneBit like so:

number ^ (Integer.highestOneBit(number) >> (bitNum-1)); This will work exactly as you have in the example, though be careful when number=0.

You can do this with xor masking.

You can do it the following:

int a = 0b101;
System.out.println(a);
int b = a ^ 0b001;
System.out.println(b);

Here the a ^ 0b001 xors all bits and thus flips the least significant bit.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top