Java - How do I get a certain bit of a short?

java

#1

Hi guys,
sorry if this is the wrong category.

There is an exercise I can’t get my head around.
Given :
A short bames flags
byte k
Another variable b

I need to know a certain bit of flags, Flags is a random number. The bit is defined by byte k.So if k = 3 it’s the third bit of the short. I need to get the value of the bit and save it in variable b.

I tried to get my head around it and while came up with different ideas but none of them works out completely as intended. I dont know how to combine byte k with the short. I’m still a beginner so everything helps.

`public class Flags2 {


    public static void main(String[] args) {

        short flags = 138;
        byte k = 3;
        boolean Bit;


      Bit = ((flags >> k)) == 1;
        if(true) {
            System.out.println("Bulb is switched on!");}
        if(false){
                System.out.println("Bulb is switched off");
        }

        System.out.println(Integer.toBinaryString(138));

    }

}`

or

public class Flags {

    public static void main(String[] args) {

        short flags = 15879;
        byte k = 2;
        int b =  flags &0b0100000000000;


        System.out.println(Integer.toBinaryString(15879));  //Ausgabe meines Flags-Wertes in Binär: 11111000000111
        // Bit 12 entspricht 1

       

        if ((flags &0b0100000000000) >=0)
        {

            System.out.println("Bulb is switched on");

        }
    }
}

#2

Style tip… The convention is to give ordinary variables lowercase names.

Bit  =>  bit

Your if statements are incorrect.

if (flags >> (k - 1)  == 1) {
    System.out.println("Bulb is switched on!");
} else {
    System.out.println("Bulb is switched off!");
}

#3

Thanks for your answer. With the changed statements the program gives me only the else-output.
The number I chose for short is 138, converted to Binary it’s: 10001010
I tried different values for byte k and the output is always the same,“Bulb is switched off!”


#4

The if statement is suspect.

The comparison value of 1 would be the result if the last bit is shifted all the way to the right. A right shift is the equivalent of floor dividing by 2.

There is a cheat approach, though. As you are shifting the kth bit to the 1’s position, flags will be odd if the bit is set, and even otherwise.

if (flags >> (k - 1) % 2) {
    // on
} else {
    // off
}

Another approach would be to create a mask and use AND to check the kth bit.

if (flags & 0b1 << (k - 1)) {
    // on
} else {
    // off
}

The above is more pseudo code than Java. Recall that bit 1 does not get shifted, that is why, k - 1.


Recall that the highest order bit is on the left, so bit 1 is the 1’s bit, bit 2 is the 2’s bit, and the bits are then counted from right to left. Bit 3 is binary 4, bit 4 is binary 8, bit 5 is binary 16, and so on.

0b10001010  =>  bit 3 (4's bit) is not set