zxingwp7.common.BitSource.readBits C# (CSharp) Method

readBits() public method

public readBits ( int numBits ) : int
numBits int number of bits to read ///
return int
        public int readBits(int numBits)
        {
            if (numBits < 1 || numBits > 32)
            {
                throw new ArgumentException();
            }

            int result = 0;

            // First, read remainder from current byte
            if (bitOffset > 0)
            {
                int bitsLeft = 8 - bitOffset;
                int toRead = numBits < bitsLeft ? numBits : bitsLeft;
                int bitsToNotRead = bitsLeft - toRead;
                int mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
                result = (bytes[byteOffset] & mask) >> bitsToNotRead;
                numBits -= toRead;
                bitOffset += toRead;
                if (bitOffset == 8)
                {
                    bitOffset = 0;
                    byteOffset++;
                }
            }

            // Next read whole bytes
            if (numBits > 0)
            {
                while (numBits >= 8)
                {
                    result = (result << 8) | (bytes[byteOffset] & 0xFF);
                    byteOffset++;
                    numBits -= 8;
                }

                // Finally read a partial byte
                if (numBits > 0)
                {
                    int bitsToNotRead = 8 - numBits;
                    int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
                    result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead);
                    bitOffset += numBits;
                }
            }

            return result;
        }

Usage Example

 private static int parseECIValue(BitSource bits)
 {
     int firstByte = bits.readBits(8);
     if ((firstByte & 0x80) == 0)
     {
         // just one byte
         return firstByte & 0x7F;
     }
     else if ((firstByte & 0xC0) == 0x80)
     {
         // two bytes
         int secondByte = bits.readBits(8);
         return ((firstByte & 0x3F) << 8) | secondByte;
     }
     else if ((firstByte & 0xE0) == 0xC0)
     {
         // three bytes
         int secondThirdBytes = bits.readBits(16);
         return ((firstByte & 0x1F) << 16) | secondThirdBytes;
     }
     throw new ArgumentException("Bad ECI bits starting with byte " + firstByte);
 }
All Usage Examples Of zxingwp7.common.BitSource::readBits