views:

56

answers:

2

I have the following code:

OutputStreamBitWriter writer = new OutputStreamBitWriter(System.out);
writer.writeBit(1);

If I want to print the value or store it in a String, how do I do that?

A: 
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStreamBitWriter writer = new OutputStreamBitWriter(out);
writer.writeBit(1);
//bla-bla
writer.flush();
System.out.println(new String(out.toByteArray()));
Ha
-1, This answer makes assumptions about the content of the OutputStreamBitWriter (whatever that is) that are unwarranted, namely that is represents the encoding of a valid string in the platform's default character set.
GregS
heh, downvote is pretty harsh. I didn't find the answer any worse than the question, heh.
Tony Ennis
@TOny: Sorry about the question. I couldn't articulate it better. Thanks.
Nithin
I agree, downvote is too harsh. +1 to balance that (not sure I would have upvoted it otherwise)
seanizer
@seanizer: If OutputStreamBitWriter operates they way you think it does then this answer is a bug.
GregS
As GregS said this won't work as the OP expects.
Grodriguez
+2  A: 

You need to do something like this:

ByteArrayOutputStream out = new ByteArrayOutputStream(); 
OutputStreamBitWriter writer = new OutputStreamBitWriter(out); 
writer.writeBit(1);
byte[] bytes = out.getBytes();
// Format and output the bytes.

Now since I suspect this is homework, I'm not going to spoon-feed you the complete solution. But here's a hint: if you try to turn the bytes into a String, the chances are that it will contain non-printing characters.

Stephen C
Yes. I am trying to implement Huffman code as a part of my homework. I have been trying to print the bits to test my code. Thanks for your pointer. I don't need the entire solution, just wanted some clue.
Nithin