Last active
December 17, 2015 21:49
-
-
Save hisui/5677268 to your computer and use it in GitHub Desktop.
Maybe it has bugs..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jp.segfault.io; | |
import java.io.EOFException; | |
import java.io.IOException; | |
import java.io.InputStream; | |
public class BitReader { | |
private InputStream in; | |
private long data; | |
private int size; | |
private final byte[] b = new byte[8]; | |
public BitReader(InputStream in) { | |
this.in = in; | |
} | |
public long get(int n) throws IOException { | |
if(n > 64) { | |
throw new IllegalArgumentException("n > 64 --> " + n); | |
} | |
long dest = 0; | |
if(n > size) { | |
dest = data << (n -= size); | |
int need = (n + 7) / 8; | |
data = readFully(need); | |
size = need * 8; | |
} | |
if(n > 0) { | |
dest |= data >>> (size -= n); | |
data &= ~(-1L << size); | |
} | |
return dest; | |
} | |
private long readFully(int n) throws IOException { | |
assert(n <= 8); | |
if(in.read(b, 0, n) != n) { | |
throw new EOFException(); | |
} | |
long dest = 0; | |
for(int i = 0; i < n; ++i) { | |
dest <<= 8; | |
dest |= (long)(b[i] & 0xff); | |
} | |
System.err.println("readFully:"+ dest); | |
return dest; | |
} | |
public void clear() { | |
data = 0; | |
size = 0; | |
} | |
@Override | |
public String toString() { | |
return "BitReader{data="+ Long.toBinaryString(data) +",size="+ size +"}"; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jp.segfault.io; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
public class BitWriter { | |
private OutputStream out; | |
private int remData; | |
private int remSize; // < 8 | |
public BitWriter(OutputStream out) { | |
this.out = out; | |
} | |
public void put(long data, int size) throws IOException { | |
if(size > 64) { | |
throw new IllegalArgumentException("n > 64 --> " + size); | |
} | |
long tmp = remData; | |
data |= tmp << size; | |
int div = (remSize + size) / 8; | |
int mod = (remSize + size) % 8; | |
if (mod != 0) { | |
remData = (int)(data & ~(-1L << mod)); | |
data >>= mod; | |
data |= tmp << size - mod; | |
} | |
remSize = mod; | |
while(div > 0) { | |
out.write((byte)(data >> 8 * --div)); | |
} | |
} | |
public void clear() { | |
remData = 0; | |
remSize = 0; | |
} | |
public void flush() throws IOException { | |
if(remSize > 0) { | |
out.write((remData << 8 - remSize) & 0xff); | |
} | |
remData = 0; | |
remSize = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment