在此问题中,我采用字符'0'和'1' 我也可以采用“ 0011001”之类的字符串 我将它们存储在缓冲区中,但是我需要将true和false更改为1和0之类的字节。
{我需要OutputByte方法的帮助。}
public class BitOutputStream {
Stack<Boolean> buffer;
OutputStream os;
BitOutputStream(OutputStream file) {
buffer = new Stack<Boolean>();
os = file;
}
public void WriteBit(char bit) throws IOException {
if (bit == '0') buffer.push(false);
else buffer.push(true);
}
//Needs to take care both of the scenarios
public void WriteBit(String bit) throws IOException {
if (bit == "0") buffer.push(false);
else buffer.push(true);
OutputByte();
}
//When the close() method is called, output whatever bits are in the buffer (even if less than 8).
public void close() throws IOException {
os.close();
}
//Turning boolean buffer to byte
private void OutputByte() {
}
}
答案 0 :(得分:0)
byte total = 0;
int multiplier = 0;
while(!buffer.empty()) {
total += buffer.pop() ? Math.pow(2, multiplier) : 0;
multiplier++;
}
System.out.println(total);