0

Let's say I have a byte:

byte myByte = 0;

This is what the bits look like in my byte:

0 0 0 0    0 0 0 0

Now I'm going to set my byte to 1, which looks like this:

0 0 0 0    0 0 0 1

Or 3:

0 0 0 0    0 0 1 1

Or 7:

0 0 0 0    0 1 1 1

What I am trying to figure out is how to set specific bits in my byte. For example:

byte myByte = 0;
// 0 0 0 0    0 0 0 0
if(a_first_statement){
    // set the first bit to `1`
    // 0 0 0 0    0 0 0 1
}

if(a_second_statement){
    // set the second bit to `1`
    // 0 0 0 0    0 0 1 0
}

if(a_third_statement){
    // set the third bit to `1`
    // 0 0 0 0    0 1 0 0
}

I would like to do this for these cases:

a_first_statement-> 0 0 0 0    0 0 0 1 // int 1
a_second_statement -> 0 0 0 0    0 0 1 0 // int 2
a_first_statement && a_second_statement -> 0 0 0 0    0 0 1 1 // int 3
a_third_statement -> 0 0 0 0    0 1 0 0 // int 4
a_first_statement && a_third_statement -> 0 0 0 0    0 1 0 1 // int 5
a_second_statement && a_third_statement -> 0 0 0 0    0 1 1 0 // int 6
a_first_statement && a_second_statement && a_third_statement -> 0 0 0 0    0 1 1 1 // int 7

I have tried different iterations of &, |, <<, and >>

byte myByte = 0;
System.out.println(myByte); // prints 0
System.out.println(myByte & 1); // prints 0
System.out.println(myByte | 1); // prints 1
System.out.println(myByte << 1); // prints 0
System.out.println(myByte >> 1); // prints 0

But nothing seems to be giving me what I want.

EDIT: I know this post has been marked as a duplicate by "Jacob G", but the link he provided didn't address my specific situation. I found those answers in my search, but I, obviously, didn't understand them enough to apply to my situation.

Brian
  • 1,726
  • 2
  • 24
  • 62
  • 1
    Think powers of 2. Going from right to left, to set the first bit, Or it with 1. The second, or it with 2, the third or it with 4. In this last case it would be `myByte |= 4`. To turn off a specific bit, And it with the complement of the power of 2. So to turn off the third bit from the right, `myByte &= ~4` – WJS Sep 18 '19 at 17:34
  • Since you are still stuck, I will help you a bit. Try using `myByte |= (1 << 0); ` which will be your first case that sets the first bit. Change the 0 to the bit you want to set such as `myByte |= (1 << 1);` to set second bit. – Nexevis Sep 18 '19 at 17:36
  • 1
    @Nexevis - *I will help you a bit* :) – WJS Sep 18 '19 at 17:38
  • 1
    @WJS Oh wow did not even notice I made a pun. Completely unintentional! – Nexevis Sep 18 '19 at 17:38
  • @WJS That was it ... thanks! I ended up with this: `selection = (byte) (selection | (1 << 0) & 0xff);` and `selection = (byte) (selection | (1 << 1) & 0xff);` and `selection = (byte) (selection | (1 << 2) & 0xff);`. I added the `&0xff` because SonarLint suggested it. – Brian Sep 18 '19 at 20:39

0 Answers0