Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit manipulation and output in Java

If you have binary strings (literally String objects that contain only 1's and 0's), how would you output them as bits into a file?

This is for a text compressor I was working on; it's still bugging me, and it'd be nice to finally get it working. Thanks!

like image 763
echoblaze Avatar asked Sep 18 '08 15:09

echoblaze


2 Answers

Easiest is to simply take 8 consecutive characters, turn them into a byte and output that byte. Pad with zeros at the end if you can recognize the end-of-stream, or add a header with length (in bits) at the beginning of the file.

The inner loop would look something like:


byte[] buffer = new byte[ ( string.length + 7 ) / 8 ];
for ( int i = 0; i < buffer.length; ++i ) {
   byte current = 0;
   for ( int j = 7; j >= 0; --j )
       if ( string[ i * 8 + j ] == '1' )
           current |= 1 << j;
   output( current );
}

You'll need to make some adjustments, but that's the general idea.

like image 179
Tomer Gabel Avatar answered Sep 27 '22 21:09

Tomer Gabel


If you're lucky, java.math.BigInteger may do everything for you.

String s = "11001010001010101110101001001110";
byte[] bytes = (new java.math.BigInteger(s, 2)).toByteArray();

This does depend on the byte order (big-endian) and right-aligning (if the number of bits is not a multiple of 8) being what you want but it may be simpler to modify the array afterwards than to do the character conversion yourself.

like image 39
finnw Avatar answered Sep 27 '22 21:09

finnw