From f8a3eb7320fd1cc6c618a79d22743fbd86f69acc Mon Sep 17 00:00:00 2001 From: Project Nayuki Date: Thu, 23 Nov 2017 03:45:16 +0000 Subject: [PATCH] Implemented bit buffer class. --- src/io/nayuki/fastqrcodegen/BitBuffer.java | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/io/nayuki/fastqrcodegen/BitBuffer.java diff --git a/src/io/nayuki/fastqrcodegen/BitBuffer.java b/src/io/nayuki/fastqrcodegen/BitBuffer.java new file mode 100644 index 0000000..c612029 --- /dev/null +++ b/src/io/nayuki/fastqrcodegen/BitBuffer.java @@ -0,0 +1,56 @@ +package io.nayuki.fastqrcodegen; + +import java.util.Arrays; + + +final class BitBuffer { + + /*---- Fields ----*/ + + private int[] data; + + private int bitLength; + + + + /*---- Constructors ----*/ + + public BitBuffer() { + data = new int[64]; + bitLength = 0; + } + + + + /*---- Methods ----*/ + + public int getBit(int index) { + if (index < 0 || index >= bitLength) + throw new IndexOutOfBoundsException(); + return (data[index >>> 5] >>> ~index) & 1; + } + + + public void appendBits(int val, int len) { + if (len < 0 || len > 31 || val >>> len != 0) + throw new IllegalArgumentException("Value out of range"); + + if (bitLength + len + 1 > data.length << 5) + data = Arrays.copyOf(data, data.length * 2); + assert bitLength + len <= data.length << 5; + + int remain = 32 - (bitLength & 0x1F); + assert 1 <= remain && remain <= 32; + if (remain < len) { + data[bitLength >>> 5] |= val >>> (len - remain); + bitLength += remain; + assert (bitLength & 0x1F) == 0; + len -= remain; + val &= (1 << len) - 1; + remain = 32; + } + data[bitLength >>> 5] |= val << (remain - len); + bitLength += len; + } + +}