-1

Given a number, i want to toggle the bits of number 'n'
say for example if n = 6 -> 0110
i want to get, result = 9 -> 1001
toggle , i.e
convert 1 to 0 & convert 0 to 1 in the binary representation
how to do this programmatically in java, by doing XOR of num with 1's
Thanks all for answers, so it depends of how many bits i want to toggle
say for ex, if its 8 bits then 0xff
if its entire 32 bits then oxffffffff
1 way would be n ^ ~0

src3369
  • 1,839
  • 2
  • 17
  • 18
  • 1
    @OldCurmudgeon this is pretty clear not the logical exclusive operator. Can you find an actual duplicate question? – matt Jan 15 '18 at 10:04
  • the question is not about XOR (exclusive or), it is how to toggle bits using XOR – src3369 Jan 15 '18 at 10:10
  • 2
    I gave an example, but it also depends on how many bits you want to toggle. eg in your example you have limited it to 4 bits. Do you want to use a full integer? – matt Jan 15 '18 at 10:12
  • @matt : yes, thank you, just gave the example of 6, so for entire integer (32 bit) it will be ` n ^ 0xffffffff` – src3369 Jan 15 '18 at 10:16
  • 1
    @src3369 I agree it's not a duplicate and should never have been marked as such, but nevertheless, the way it's worded, this question is too trivial. It's akin to "I know what the plus (+) operator does, but how can I use it to add two numbers together?" If you can reword the question to explain what exactly is causing difficulty, it may get more meaningful answers. – DodgyCodeException Jan 15 '18 at 10:18
  • 1
    Maybe you want the ones-complement: `~6 == 0b111...111001` == -6-1 == -7`. – Joop Eggen Jan 15 '18 at 10:30
  • 1
    [How do you set, clear, and toggle a single bit?](https://stackoverflow.com/q/47981/995714) – phuclv Jan 15 '18 at 10:40
  • Lưu Vĩnh Phúc's link is very useful and, although it's C and C++, it's still relevant to Java. The main differences being that Java doesn't have unsigned ints but instead has the `>>>` operator. – DodgyCodeException Jan 15 '18 at 10:47

2 Answers2

2

You could do exactly that.

int y = 6^0xf

If you want to use the full int, then you have to XOR with -1 (twos complement means this is all 1's).

int y = 6^-1;

You can also use a different representation to make writing it out more intuitive.

int mask = 0xffffffff; //also -1
matt
  • 10,892
  • 3
  • 22
  • 34
2
   public static void main(final String[] args) {
        final int n = 0b0110;
        System.out.println(Integer.toBinaryString(n));
        final int m = n ^ 0xffffffff;
        System.out.println(Integer.toBinaryString(m));
    }
  • The XOR will give a different result depending on the number of 1's. In ops example the result is 9, in your example you get -7. – matt Jan 15 '18 at 10:11