如何将一堆布尔值转换为字节值?

时间:2019-02-12 14:01:33

标签: java stack boolean byte

在此问题中,我采用字符'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() {
    }
}

1 个答案:

答案 0 :(得分:0)

byte total = 0;
int multiplier = 0;

while(!buffer.empty()) {
    total += buffer.pop() ? Math.pow(2, multiplier) : 0;
    multiplier++;
}

System.out.println(total);