java-org.hwo/src/org/hwo/buffer/BitStream.java

113 lines
1.5 KiB
Java

package org.hwo.buffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BitStream {
private boolean byteOrder;
private int pByte;
private byte pBit;
private List<Byte> buffer;
public BitStream()
{
initialize();
buffer = new ArrayList<Byte>();
}
public BitStream(byte[] source)
{
initialize();
buffer = new ArrayList<Byte>();
for (byte b:source)
buffer.add(b);
}
public BitStream(Byte[] source)
{
initialize();
buffer = new ArrayList<Byte>(Arrays.asList(source));
}
private void initialize()
{
pByte = 0;
pBit = 0;
}
private short unsigned2short(byte by)
{
short s;
if (by < 0)
{
s = (short)(128 | (by & 0x7f));
} else
s = by;
return s;
}
public short read(byte bits)
{
short symbol = 0;
byte position = 0; // Bit-Position im symbol
while (bits > 0)
{
symbol <<= 1;
short s = (short)( unsigned2short(buffer.get(pByte)));
if (byteOrder)
{
s >>= pBit;
if ((s & 0x01) == 0x01)
symbol |= 0x01;
} else
{
s <<= pBit;
if ((s & 0x80) == 0x80)
symbol |= 0x01;
};
pBit++;
if (pBit == 8)
{
pBit = 0;
pByte++;
}
bits--;
}
return symbol;
}
public byte[] getBuffer()
{
int len = buffer.size();
byte[] out = new byte[ len ];
for (int i=0;i<len;i++)
out[i] = buffer.get(i);
return out;
}
public boolean isByteOrder() {
return byteOrder;
}
public void setByteOrder(boolean byteOrder) {
this.byteOrder = byteOrder;
}
}