Java BitSet - wrapper to put chars/Strings in
I'm making use of BitSet in Java to store values I have to serialize and deserialize into/from lower abstraction levels. This is to create a file-format container.
Currently I want to store a String into a BitSet:
private BitSet string_to_bit(String content_string) {
BitSet result = new BitSet(this.size);
char[] content_string_arr = new char[conte开发者_如何学运维nt_string.length()];
for (char c : content_string_arr) {
int tmp = (int) c;
result += Integer.toBinaryString(tmp);
}
}
The += is undefined on a BitSet, so the code is wrong at that point. Afaik I cannot override operators in Java 6. How would you elegantly wrap that operation? I don't want to end up repeating all these low level conversions over and over again because as it seems they repeat. Is there any .toBit equivalent? I can cast a BitSet to String with toString(). Why is there no de-abstraction?
Best, Marius
as far as I know there is not .toBit()
equivalent. you should write your own implementtation.
Here are 2 links may be helpful to you that Converting Between a BitSet and a Byte Array
and Convert bitset to int array and string
I find it quite odd that you are using a BitSet for serialization. It's not really designed for this. I'd suggest altering this approach first of all, as it will save you a lot of pain in the long run.
Have you considered using a DataOutputStream instead? This is a much more standard approach and has the advantages that all the utility methods needed for writing Strings and other data types are already there for you to use....
It appears to be that your code won't do what you want. For a start, your array will always be full of \0 (nul) characters. Perhaps what you intended is much simpler.
I suspect there is no simple way to do what you want because BitSet isn't intended to store text. Perhaps you intended
private static byte[] string_to_bytes(String text) {
return text.getBytes();
}
Normally files contain bytes rather than bits.
Is your data byte aligned? You could use a ByteBuffer.
As far as I know java does not provide functions or classes for bit level I/O.
精彩评论