Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

converting a byte array to a bitset

Status
Not open for further replies.

dendenners

Programmer
Jul 17, 2001
110
IE
Hey there,
Does anyone have a method to convert a byte array to a bitset? I have one but it doesn't seem to work properly. Thanks.
 
No but I could write one easily enough. First of all, you have to decide what your rules are for turning a byte into a bit. Does a 0 byte equate to a 0 bit and a non zero byte equate to a 1 bit? That's what I will do:

public BitSet byteArrayToBitSet(byte [] bits)
{
int length = bits.length;
BitSet set = new BitSet(length);
for (int i = 0; i < length; i++)
{
if (bits != 0)
set.set(i);
}
return set;
}
 
Hey there,
No I need to convert each byte to its bit representation, and then put each individual converted bit into the bitset. The reason I ask is that I have one example but I'm not sure if its working properly. Here it is:

public static BitSet byte2BitSet
(byte[] b, int offset, boolean bitZeroMeansExtended)
{
int len = bitZeroMeansExtended ?
((b[offset] & 0x80) == 0x80 ? 128 : 64) : 64;

BitSet bmap = new BitSet (len);
for (int i=0; i<len; i++)
if (((b[offset + (i >> 3)]) & (0x80 >> (i % 8))) > 0)
bmap.set(i+1);
return bmap;
}
}
Thanks a lot.
 
So, are you saying that if you had four bytes then you want 32 bits in the bitset? How do you want it represented? Big endian or little endian?
 
Thanks for the input. I discovered the above method works fine, the problem I had was in a different part of the code.
 
Thanks, I was really looking for a function like this. Now I only need more functions to work with bits. To check if a bitset is, say, 1010, I'll have to do:

if (bitset.get(0) && !bitset.get(1) && bitset.get(2) && !bitset.get(3)) { my_lucious_function(); }

Lots of job if I have to check for occurances of bit combinations in larger maps... Any better ideas?
 
Create the bitset that you are looking for and do a comparison:

BitSet lucious = new BitSet();
lucious.set(0);
lucious.set(2);

...

if (bitset.equals(lucious) {my_lucious_function();}

You can create a different bitset object for each 'switch' that you want to do.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top