To check if a specific bit is 0 or 1 in a long value in Java, you can use bitwise operations, specifically the bitwise AND (&) operator. Here's how you can do it:
Suppose you have a long value number and you want to check the nth bit (0-based index) from the right:
public class BitCheckExample { public static void main(String[] args) { long number = 12345L; // Your long value int bitIndex = 3; // The bit index to check (0-based index) // Create a mask with the bit of interest set to 1 and all other bits set to 0 long mask = 1L << bitIndex; // Use the bitwise AND operator to check if the bit is 0 or 1 boolean isBitSet = (number & mask) != 0; // Print the result if (isBitSet) { System.out.println("Bit at index " + bitIndex + " is 1."); } else { System.out.println("Bit at index " + bitIndex + " is 0."); } } } In this example:
We have a long value called number.
We specify the index of the bit we want to check using the bitIndex variable (0-based index).
We create a bitmask (mask) by left-shifting 1 by bitIndex positions. This sets the bit of interest to 1 and leaves all other bits as 0.
We use the bitwise AND (&) operator to perform a bitwise AND operation between number and mask. If the result is non-zero, it means that the bit at the specified index is 1; otherwise, it is 0.
We print the result based on whether the bit is set or not.
You can adjust the bitIndex variable to check different bits within the number value.
core mediarecorder new-operator unique-values .htaccess threadpoolexecutor count-unique homekit nginfinitescroll privileges