Saturday, 15 September 2012

hex - Java bit comparison, bitset? -



hex - Java bit comparison, bitset? -

i've got word 'bitset' stuck in head solution problem think might getting myself confused.

i've got list of hex values indicate conditions, such as:

0x0001 = outside 0x20000000 = blah...

now i'm reading in int, , want compare int against of existing hex conditions see matches. can match zero, one, or many.

is bitset want, or there simpler way of doing it?

i sense bit silly asking this, can't remember sodding thing called! :)

many thanks

are looking bitmasking? each bit in int represents boolean value, set (1, means true) , unset (0, means false). example:

public class maskingexample { private static final int outside_mask = 1; // right-most bit private static final int heated_mask = 1 << 1; // second-to-right-most bit private static final int wet_mask = 1 << 2; // third-to-right-most bit private int value = 0; public boolean isoutside() { homecoming isbitset(outside_mask, value); } public void setoutside(boolean outside) { value = outside ? setbit(outside_mask, value) : unsetbit(outside_mask, value); } // other setters , getters private static int setbit(int mask, int value) { homecoming value | mask; } private static int unsetbit(int mask, int value) { homecoming value & ~mask; } private static boolean isbitset(int mask, int value) { homecoming (value & mask) == mask; } }

if need more 32 conditions, utilize long masks , value, , add together l each of 1 values beingness shifted, , can have 64 conditions, this:

private static final long outside_mask = 1l; // right-most bit private static final long heated_mask = 1l << 1; // second-to-right-most bit private static final long wet_mask = 1l << 2; // third-to-right-most bit private long value = 0;

you can set more 1 bit @ time too, way. combine masks single mask using &:

public void setoutsideandraining(boolean outsideandraining) { int combomask = outside_mask & wet_mask; value = outsideandraining ? setbit(combomask, value) : unsetbit(combomask, value); }

edit: after seeing kaliatech's reply below, utilize bitset. solution similar, math logic encapsulated in bitset object , allows arbitrary number of bits aren't limited 64.

public class maskingexample { private static final int outside_position = 0; private static final int heated_position = 1; private static final int wet_position = 2; private static final int total_conditions = 3; private bitset bitset = new bitset(total_conditions); public boolean isoutside() { homecoming bitset.get(outside_position); } public void setoutside(boolean outside) { bitset.set(outside_position, outside); } // other setters , getters }

java hex logic bits bitset

No comments:

Post a Comment