2

I'm having trouble getting a bit to work properly in java6...I'm trying to write a compression program that will write bits to a compressed file...so for example a common letter such as "e" might just be the binary sequence "101" in ascii

I think the fileOutputStream.write(int) method is what I'm going to want to accomplish this, but how to I represent a sequence of bits as in int?

1
  • Do you need it bit-wise? meaning that you could put 2 'e's into the stream and still have 2 bits left of that byte? then you would need to define how many bits per information etc. Take a look at bit shifting: docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html Commented Nov 24, 2011 at 16:46

2 Answers 2

3

You can use BitSet. And then write a full byte array using FileOutputStream#write(byte\[\]) like that:

fileOutputStream.write(myBitSet.toByteArray());
Sign up to request clarification or add additional context in comments.

7 Comments

BTW, I gave links to Java 7 docs, but it is valid in Java 6 as well.
Ummm, that can't be the simplest way to write e to a stream. ;)
Im unfamiliar with the (byte[]) notation, and I know Bitsets are vectors, is that a special notation of vectors? EDIT: I just see what I did sorry im silly :P
@PeterLawrey - of course, but this is a way to "represent a sequence of bits"
@SetSlapShot - byte[] means byte array.
|
0

101 is the ascii value for 'e'

All you have to is write it

FileOutputStream fos =
fos.write('e'); // writes 101 which is the ascii for 'e'

2 Comments

That actually writes '00000101'. Don't know if OP wants that :-/
In binary, but e is (byte) 101 in ascii rather than 0b101

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.