bit manuplation

A

ali4ever4

well hi ther i have alittle advanced question about bitmanuplation

if i have a set of bits such as 10110011

which can be any thing arrays of 1 and 0 or may be string or mostly
BitSet

is there is away to convert it to byte or may be to any other premitive
type such as int or char with the rest of the bits be zeros ??!!
hope i will find an answer to my question
 
C

Chris Smith

well hi ther i have alittle advanced question about bitmanuplation

if i have a set of bits such as 10110011

which can be any thing arrays of 1 and 0 or may be string or mostly
BitSet

You've got answers for String. As for BitSet, the following should
work:

public int bitsetToInt(BitSet bitset)
{
if (bitset.length() > 32) throw new IllegalArgumentException();

int result = 0;
for (int i = 0; i < 32; i++)
{
if (bitset.get(i)) result |= (1 << i);
}

return result;
}

Of course, this code will fail if there are more than 32 bits in the
BitSet. You can modify the above as appropriate for byte, short, or
long if you prefer. It makes no sense to put a bit mask in char, but if
you really wish to do so, then the same code will work.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top