Reputation: 163
Situation
What I'm trying to achieve is to store true/false represented as a bit in a Integer/Long. The problem is that I'm unable to solve if a certain bit is 1 or 0.
Code
public class Test
{
private static long unlocked = 0;
public static void main(String[] args)
{
setUnlocked(1);
setUnlocked(2);
setUnlocked(3);
System.out.println(isUnlocked(2);
}
public static void setUnlocked(int id)
{
unlocked += Math.pow(2, id);
}
public static boolean isUnlocked(int id)
{
// ???
return false;
}
}
As in the test case above, it will result in the following bits sequence: 1110 = 14.
Edit
Second Question:
public static void setUnlocked(int id)
{
unlocked |= 1 << id;
}
To
public static void setUnlocked(int id, boolean set)
{
}
That will give the option to set the bit to 0 or 1 at the given location.
But how can I achieve this?
Upvotes: 1
Views: 253
Reputation: 393841
Use bitwise operators :
public static void setUnlocked(int id)
{
unlocked |= 1L<<id; // set the id'th bit
}
public static boolean isUnlocked(int id)
{
return (unlocked & (1L<<id)) != 0; // get the id'th bit
}
1<<id
is the fastest way to compute 2^id.
bitwise OR (|) lets you set a bit in the int.
bitwise AND (&) lets you get the value of a bit (by clearing all the other bits and checking if the result is not 0).
EDIT :
public static void setUnlocked(int id, boolean set)
{
if (set) {
unlocked |= 1L<<id; // set the id'th bit
} else {
unlocked &= 0xffffffffffffffffL ^ (1L<<id); // clear the id'th bit
}
}
Upvotes: 6
Reputation: 20059
A more flexible approach is to use a plain simple Set<Integer>
:
static Set<Integer> unlocked = new HashSet<>();
public static void setUnlocked(int id) {
unlocked.add(id);
}
public static boolean isUnlocked(int id) {
return unlocked.contains(id);
}
This approach does not rely on id's to be in any particular range. For thread safety, synchronize on the Set
if needed.
Upvotes: 1