質問
場合はバイナリ文字列(文字通りの文字列を含むオブジェクトを1と0)、あなたは何点ぐらいになると思い出力としてのビットへのファイルとは何ですか?
これはテキストコンプレッサか;まだまだbuggingく、思いもよります。よろしく!
解決
最も簡単なのは単に8年連続文字をバイトを出力するバイトです。パッドをゼロにできると認識のストリーム、または追加ヘッダーの長さ(ビット単位)の先頭にファイルです。
内側のループを見ようなもの:
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 );
}
る必要がありますが、調整がそのアイデアです。
他のヒント
運が良ければ、java.math.BigIntegerが尽くします。
String s = "11001010001010101110101001001110";
byte[] bytes = (new java.math.BigInteger(s, 2)).toByteArray();
これは、バイト順(ビッグエンディアン)で、右揃えの場合、ビット数が8の倍数にしておいて欲しい作用を引き起こす場合もある単純な変更の配列、その後ように文字を変換す。
public class BitOutputStream extends FilterOutputStream
{
private int buffer = 0;
private int bitCount = 0;
public BitOutputStream(OutputStream out)
{
super(out);
}
public void writeBits(int value, int numBits) throws IOException
{
while(numBits>0)
{
numBits--;
int mix = ((value&1)<<bitCount++);
buffer|=mix;
value>>=1;
if(bitCount==8)
align8();
}
}
@Override
public void close() throws IOException
{
align8(); /* Flush any remaining partial bytes */
super.close();
}
public void align8() throws IOException
{
if(bitCount > 0)
{
bitCount=0;
write(buffer);
buffer=0;
}
}
}
そして...
if (nextChar == '0')
{
bos.writeBits(0, 1);
}
else
{
bos.writeBits(1, 1);
}
を想定した文字列が複数のビット(きパッドでそのJavaの造解析の整数です。valueOf方法でなんとかこのように:
String s = "11001010001010101110101001001110";
byte[] data = new byte[s.length() / 8];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) Integer.parseInt(s.substring(i * 8, (i + 1) * 8), 2);
}
その対応することができるでしょう書くのバイトを FileOutputStream
かが簡単に手に入る。
一方、がんの殆どが、考えを用いない文字列店のビットが、バイトを直接圧縮器です。
所属していません StackOverflow