views:

59

answers:

1

I'm trying to implement some compression algorithms, and I need to deal with bits in Java.

What I need to do is that when I write the value 1 then the value 2, those numbers are stored in the file as bits, so the file size will be 1 byte instead of 2, as 1 is stored in 1 bit and 2 is stored in 2 bits.

Is it possible? Thanks very much

+1  A: 

All the I/O methods have a byte as the lowest granularity. You can write bits, but you have to pack them into bytes by yourself. Maybe a one-byte buffer that you write out to the file once it fills up would be appropriate.

Also note that there is no way to know the length of the file in bits (you do not know if the last byte was "full"). So your application needs to take care of that somehow.

You can also google for "BitOutputStream", of which there are a few, though not in libraries that are very common. Maybe just use one of those.

Finally, the file you will be creating will not be a "Text" file, it will be very much binary (even more so than usual...)

Thilo
BitOutputStream did the trick, thanks very much :)
Islam Hassan
http://sourceforge.net/projects/jflac/ ... For anyone who'll use it, don't forget to call object.flushByteAligned() after writing so as to get your work implemented
Islam Hassan