I am trying to solve a problem that involves basically implementing a logical AND between the input parameter.
The complexity of the problem involves the size of the input parameters. To give a high level overview, I am trying to implement the logic similar to
100 & 100 == 100
001 & 010 == 0
001 & 100 == 0
.....
The complexity is that some of the input parameters can be 400 bits long. Its not a true binary number representation. It's more of a positional representation. The same input can be represented as
100 = x1; (or) x100
011 = x2,3; (or) x011
001.......11 = x3,......450,451;
So basically "x" is just a prefix with the value for it. This is an ACL system designed a long time ago and I am trying to implement a Java version for it.
I couldn't find a data type in Java that could be used to represent a binary representation that is as huge as having 400 bits. I can also use the decimal representation [ie., x2,3] and solve it too, but I couldn't think of way other than looping through the entire number range and comparing it with the other input parameter. Both input parameters could be normalized to the same representation format [ie., binary or decimal].
Any suggestions (or) help on how I can solve this problem?
You could use a BitSet
. It has support for bitwise and-operations and should handle 400 bits quite well.
Here is an example:
BitSet bs1 = new BitSet();
bs1.set(2);
bs1.set(5);
bs1.set(7);
bs1.set(8);
BitSet bs2 = new BitSet();
bs2.set(2);
bs2.set(7);
bs2.set(9);
bs1.and(bs2);
// Prints {2, 7}
System.out.println(bs1);
To parse a x110101
string, you could do something like
String acl = "x110101";
BitSet bs1 = new BitSet();
for (int i = 1; i < acl.length(); i++)
if (acl.charAt(i) == '1')
bs1.set(i);
If you still don't like that approach, you could use a Set<Integer>
containing the indecies of the ones. To figure out the "and" between two such sets, you simply do set1.retainAll(set2)
.
Here is an example:
Set<Integer> bs1 = new HashSet<Integer>();
bs1.add(2);
bs1.add(5);
bs1.add(7);
bs1.add(8);
Set<Integer> bs2 = new HashSet<Integer>();
bs2.add(2);
bs2.add(7);
bs2.add(9);
bs1.retainAll(bs2);
// Prints [2, 7]
System.out.println(bs1);
java.util.BitSet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With