Пример #1
0
        private static bool decodeByteSegment(BitSource bits,
                                              StringBuilder result,
                                              int count,
                                              CharacterSetECI currentCharacterSetECI,
                                              IList <byte[]> byteSegments,
                                              IDictionary <DecodeHintType, object> hints)
        {
            // Don't crash trying to read more bits than we have available.
            if (count << 3 > bits.available())
            {
                return(false);
            }

            byte[] readBytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (byte)bits.readBits(8);
            }
            String encoding;

            if (currentCharacterSetECI == null)
            {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.
                encoding = StringUtils.guessEncoding(readBytes, hints);
            }
            else
            {
                encoding = currentCharacterSetECI.EncodingName;
            }
            try
            {
                result.Append(Encoding.GetEncoding(encoding).GetString(readBytes, 0, readBytes.Length));
            }
#if WindowsCE
            catch (PlatformNotSupportedException)
            {
                // WindowsCE doesn't support all encodings. But it is device depended.
                // So we try here the some different ones
                if (encoding == "ISO-8859-1")
                {
                    result.Append(Encoding.GetEncoding(1252).GetString(readBytes, 0, readBytes.Length));
                }
                else
                {
                    result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
                }
            }
#endif
            catch (Exception)
            {
                return(false);
            }
            byteSegments.Add(readBytes);

            return(true);
        }
Пример #2
0
        /**
         * See ISO 16022:2006, 5.2.8 and Annex C Table C.3
         */
        private static void decodeEdifactSegment(BitSource bits, StringBuilder result)
        {
            bool unlatch = false;

            do
            {
                // If there is only two or less bytes left then it will be encoded as ASCII
                if (bits.available() <= 16)
                {
                    return;
                }

                for (int i = 0; i < 4; i++)
                {
                    int edifactValue = bits.readBits(6);

                    // Check for the unlatch character
                    if (edifactValue == 0x2B67) // 011111
                    {
                        unlatch = true;
                        // If we encounter the unlatch code then continue reading because the Codeword triple
                        // is padded with 0's
                    }

                    if (!unlatch)
                    {
                        if ((edifactValue & 32) == 0) // no 1 in the leading (6th) bit
                        {
                            edifactValue |= 64;       // Add a leading 01 to the 6 bit binary value
                        }
                        result.Append(edifactValue);
                    }
                }
            } while (!unlatch && bits.available() > 0);
        }
Пример #3
0
        /**
         * See ISO 16022:2006, 5.2.9 and Annex B, B.2
         */
        private static void decodeBase256Segment(BitSource bits, StringBuilder result, System.Collections.ArrayList byteSegments)
        {
            // Figure out how long the Base 256 Segment is.
            int d1 = bits.readBits(8);
            int count;

            if (d1 == 0)    // Read the remainder of the symbol
            {
                count = bits.available() / 8;
            }
            else if (d1 < 250)
            {
                count = d1;
            }
            else
            {
                count = 250 * (d1 - 249) + bits.readBits(8);
            }
            byte[] bytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                bytes[i] = unrandomize255State(bits.readBits(8), i);
            }
            byteSegments.Add(bytes);
            try {
                result.Append(System.Text.Encoding.GetEncoding("iso-8859-1").GetString(bytes));
            } catch (Exception uee) {
                throw new Exception("Platform does not support required encoding: " + uee);
            }
        }
Пример #4
0
        /// <summary>
        /// See ISO 16022:2006, 5.2.8 and Annex C Table C.3
        /// </summary>
        private static void decodeEdifactSegment(BitSource bits, StringBuilder result)
        {
            do
            {
                // If there is only two or less bytes left then it will be encoded as ASCII
                if (bits.available() <= 16)
                {
                    return;
                }

                for (int i = 0; i < 4; i++)
                {
                    int edifactValue = bits.readBits(6);

                    // Check for the unlatch character
                    if (edifactValue == 0x1F)     // 011111
                    {
                        // Read rest of byte, which should be 0, and stop
                        int bitsLeft = 8 - bits.BitOffset;
                        if (bitsLeft != 8)
                        {
                            bits.readBits(bitsLeft);
                        }
                        return;
                    }

                    if ((edifactValue & 0x20) == 0) // no 1 in the leading (6th) bit
                    {
                        edifactValue |= 0x40;       // Add a leading 01 to the 6 bit binary value
                    }
                    result.Append((char)edifactValue);
                }
            } while (bits.available() > 0);
        }
Пример #5
0
 private static void decodeByteSegment(BitSource bits, System.Text.StringBuilder result, int count)
 {
     sbyte[] readBytes = new sbyte[count];
     if (count << 3 > bits.available())
     {
         throw new ReaderException("Count too large: " + count);
     }
     for (int i = 0; i < count; i++)
     {
         readBytes[i] = (sbyte)bits.readBits(8);
     }
     // The spec isn't clear on this mode; see
     // section 6.4.5: t does not say which encoding to assuming
     // upon decoding. I have seen ISO-8859-1 used as well as
     // Shift_JIS -- without anything like an ECI designator to
     // give a hint.
     System.String encoding = guessEncoding(readBytes);
     try
     {
         byte[] bytes = SupportClass.ToByteArray(readBytes);
         //System.Windows.Forms.MessageBox.Show("encodings: "+ System.Text.Encoding.());
         //UPGRADE_TODO: The differences in the Format  of parameters for constructor 'java.lang.String.String'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
         result.Append(System.Text.Encoding.GetEncoding(encoding).GetString(bytes, 0, bytes.Length));
     }
     catch (System.IO.IOException uce)
     {
         //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
         throw new ReaderException(uce.ToString());
     }
 }
        /// <summary>
        /// See ISO 16022:2006, 5.2.9 and Annex B, B.2
        /// </summary>
        private static bool decodeBase256Segment(BitSource bits,
                                                 StringBuilder result,
                                                 IList <byte[]> byteSegments)
        {
            // Figure out how long the Base 256 Segment is.
            int codewordPosition = 1 + bits.ByteOffset; // position is 1-indexed
            int d1 = unrandomize255State(bits.readBits(8), codewordPosition++);
            int count;

            if (d1 == 0)
            {
                // Read the remainder of the symbol
                count = bits.available() / 8;
            }
            else if (d1 < 250)
            {
                count = d1;
            }
            else
            {
                count = 250 * (d1 - 249) + unrandomize255State(bits.readBits(8), codewordPosition++);
            }

            // We're seeing NegativeArraySizeException errors from users.
            if (count < 0)
            {
                return(false);
            }

            byte[] bytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                // Have seen this particular error in the wild, such as at
                // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2
                if (bits.available() < 8)
                {
                    return(false);
                }
                bytes[i] = (byte)unrandomize255State(bits.readBits(8), codewordPosition++);
            }
            byteSegments.Add(bytes);
            try
            {
#if (WINDOWS_PHONE || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || WindowsCE || PORTABLE)
#if WindowsCE
                result.Append(Encoding.GetEncoding(1252).GetString(bytes, 0, bytes.Length));
#else
                result.Append(Encoding.GetEncoding("ISO-8859-1").GetString(bytes, 0, bytes.Length));
#endif
#else
                result.Append(Encoding.GetEncoding("ISO-8859-1").GetString(bytes));
#endif
            }
            catch (Exception uee)
            {
                throw new InvalidOperationException("Platform does not support required encoding: " + uee);
            }

            return(true);
        }
        private static bool DecodeKanjiSegment(BitSource bits,
                                               StringBuilder result,
                                               int count)
        {
            // Don't crash trying to read more bits than we have available.
            if (count * 13 > bits.Available())
            {
                return(false);
            }

            // Each character will require 2 bytes. Read the characters as 2-byte pairs
            // and decode as Shift_JIS afterwards
            byte[] buffer = new byte[2 * count];
            int    offset = 0;

            while (count > 0)
            {
                // Each 13 bits encodes a 2-byte character
                int twoBytes          = bits.ReadBits(13);
                int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
                if (assembledTwoBytes < 0x01F00)
                {
                    // In the 0x8140 to 0x9FFC range
                    assembledTwoBytes += 0x08140;
                }
                else
                {
                    // In the 0xE040 to 0xEBBF range
                    assembledTwoBytes += 0x0C140;
                }
                buffer[offset]     = (byte)(assembledTwoBytes >> 8);
                buffer[offset + 1] = (byte)assembledTwoBytes;
                offset            += 2;
                count--;
            }
            // Shift_JIS may not be supported in some environments:
            try
            {
                result.Append(Encoding.GetEncoding(StringUtils.SHIFT_JIS).GetString(buffer, 0, buffer.Length));
            }
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH)
            catch (ArgumentException)
            {
                try
                {
                    // Silverlight only supports a limited number of character sets, trying fallback to UTF-8
                    result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length));
                }
                catch (Exception)
                {
                    return(false);
                }
            }
#endif
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
Пример #8
0
        /**
         * See ISO 16022:2007, 5.4.1
         */
        private static bool decodeECISegment(BitSource bits, ECIStringBuilder result)
        {
            if (bits.available() < 8)
            {
                return(false);
            }
            int c1 = bits.readBits(8);

            if (c1 <= 127)
            {
                return(result.AppendECI(c1 - 1));
            }
            return(true);
            //currently we only support character set ECIs

            /*} else {
             * if (bits.available() < 8) {
             *  throw FormatException.getFormatInstance();
             * }
             * int c2 = bits.readBits(8);
             * if (c1 >= 128 && c1 <= 191) {
             * } else {
             *  if (bits.available() < 8) {
             *    throw FormatException.getFormatInstance();
             *  }
             *  int c3 = bits.readBits(8);
             * }
             * }*/
        }
Пример #9
0
        private static void DecodeByteSegment(BitSource bits, StringBuilder result, int count, CharacterSetECI currentCharacterSetECI, System.Collections.ArrayList byteSegments)
        {
            sbyte[] readBytes = new sbyte[count];
            if (count << 3 > bits.Available())
            {
                throw ReaderException.Instance;
            }
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (sbyte)bits.ReadBits(8);
            }

            // The spec isn't clear on this mode; see
            // section 6.4.5: t does not say which encoding to assuming
            // upon decoding. I have seen ISO-8859-1 used as well as
            // Shift_JIS -- without anything like an ECI designator to
            // give a hint.
            var encoding = currentCharacterSetECI == null?GuessEncoding(readBytes) : currentCharacterSetECI.EncodingName;

            try
            {
                //UPGRADE_TODO: The differences in the Format  of parameters for constructor 'java.lang.String.String'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                result.Append(Encoding.GetEncoding(encoding).GetString(SupportClass.ToByteArray(readBytes)));
            }
            catch (IOException)
            {
                throw ReaderException.Instance;
            }
            byteSegments.Add(SupportClass.ToByteArray(readBytes));
        }
Пример #10
0
        /// <summary>
        /// See specification GBT 18284-2000
        /// </summary>
        /// <param name="bits">The bits.</param>
        /// <param name="result">The result.</param>
        /// <param name="count">The count.</param>
        /// <returns></returns>
        private static bool decodeHanziSegment(BitSource bits,
                                               StringBuilder result,
                                               int count)
        {
            // Don't crash trying to read more bits than we have available.
            if (count * 13 > bits.available())
            {
                return(false);
            }

            // Each character will require 2 bytes. Read the characters as 2-byte pairs
            // and decode as GB2312 afterwards
            byte[] buffer = new byte[2 * count];
            int    offset = 0;

            while (count > 0)
            {
                // Each 13 bits encodes a 2-byte character
                int twoBytes          = bits.readBits(13);
                int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
                if (assembledTwoBytes < 0x003BF)
                {
                    // In the 0xA1A1 to 0xAAFE range
                    assembledTwoBytes += 0x0A1A1;
                }
                else
                {
                    // In the 0xB0A1 to 0xFAFE range
                    assembledTwoBytes += 0x0A6A1;
                }
                buffer [offset]     = (byte)((assembledTwoBytes >> 8) & 0xFF);
                buffer [offset + 1] = (byte)(assembledTwoBytes & 0xFF);
                offset += 2;
                count--;
            }

            try {
                result.Append(Encoding.GetEncoding(StringUtils.GB2312).GetString(buffer, 0, buffer.Length));
            }
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH)
            catch (ArgumentException)
            {
                try
                {
                    // Silverlight only supports a limited number of character sets, trying fallback to UTF-8
                    result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length));
                }
                catch (Exception)
                {
                    return(false);
                }
            }
#endif
            catch (Exception) {
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// See ISO 16022:2006, 5.2.7
        /// </summary>
        private static bool decodeAnsiX12Segment(BitSource bits,
                                                 StringBuilder result)
        {
            // Three ANSI X12 values are encoded in a 16-bit value as
            // (1600 * C1) + (40 * C2) + C3 + 1

            int[] cValues = new int[3];
            do
            {
                // If there is only one byte left then it will be encoded as ASCII
                if (bits.available() == 8)
                {
                    return(true);
                }
                int firstByte = bits.readBits(8);
                if (firstByte == 254)
                { // Unlatch codeword
                    return(true);
                }

                parseTwoBytes(firstByte, bits.readBits(8), cValues);

                for (int i = 0; i < 3; i++)
                {
                    int cValue = cValues[i];
                    if (cValue == 0)
                    { // X12 segment terminator <CR>
                        result.Append('\r');
                    }
                    else if (cValue == 1)
                    { // X12 segment separator *
                        result.Append('*');
                    }
                    else if (cValue == 2)
                    { // X12 sub-element separator >
                        result.Append('>');
                    }
                    else if (cValue == 3)
                    { // space
                        result.Append(' ');
                    }
                    else if (cValue < 14)
                    { // 0 - 9
                        result.Append((char)(cValue + 44));
                    }
                    else if (cValue < 40)
                    { // A - Z
                        result.Append((char)(cValue + 51));
                    }
                    else
                    {
                        return(false);
                    }
                }
            } while (bits.available() > 0);

            return(true);
        }
        private static bool DecodeByteSegment(BitSource bits,
                                              StringBuilder result,
                                              int count,
                                              CharacterSetECI currentCharacterSetECI,
                                              IList <byte[]> byteSegments)
        {
            // Don't crash trying to read more bits than we have available.
            if (count << 3 > bits.Available())
            {
                return(false);
            }

            byte[] readBytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (byte)bits.ReadBits(8);
            }
            String encoding;

            if (currentCharacterSetECI == null)
            {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.
                encoding = StringUtils.GuessEncoding(readBytes);
            }
            else
            {
                encoding = currentCharacterSetECI.EncodingName;
            }
            try
            {
                result.Append(Encoding.GetEncoding(encoding).GetString(readBytes, 0, readBytes.Length));
            }
            catch (ArgumentException)
            {
                try
                {
                    // Silverlight only supports a limited number of character sets, trying fallback to UTF-8
                    result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }
            byteSegments.Add(readBytes);

            return(true);
        }
Пример #13
0
        private static bool decodeNumericSegment(BitSource bits,
                                                 StringBuilder result,
                                                 int count)
        {
            // Read three digits at a time
            while (count >= 3)
            {
                // Each 10 bits encodes three digits
                if (bits.available() < 10)
                {
                    return(false);
                }
                int threeDigitsBits = bits.readBits(10);
                if (threeDigitsBits >= 1000)
                {
                    return(false);
                }
                result.Append(toAlphaNumericChar(threeDigitsBits / 100));
                result.Append(toAlphaNumericChar((threeDigitsBits / 10) % 10));
                result.Append(toAlphaNumericChar(threeDigitsBits % 10));

                count -= 3;
            }
            if (count == 2)
            {
                // Two digits left over to read, encoded in 7 bits
                if (bits.available() < 7)
                {
                    return(false);
                }
                int twoDigitsBits = bits.readBits(7);
                if (twoDigitsBits >= 100)
                {
                    return(false);
                }
                result.Append(toAlphaNumericChar(twoDigitsBits / 10));
                result.Append(toAlphaNumericChar(twoDigitsBits % 10));
            }
            else if (count == 1)
            {
                // One digit left over to read
                if (bits.available() < 4)
                {
                    return(false);
                }
                int digitBits = bits.readBits(4);
                if (digitBits >= 10)
                {
                    return(false);
                }
                result.Append(toAlphaNumericChar(digitBits));
            }

            return(true);
        }
Пример #14
0
        private static bool decodeAlphanumericSegment(BitSource bits,
                                                      StringBuilder result,
                                                      int count,
                                                      bool fc1InEffect)
        {
            // Read two characters at a time
            int start = result.Length;

            while (count > 1)
            {
                if (bits.available() < 11)
                {
                    return(false);
                }
                int nextTwoCharsBits = bits.readBits(11);
                result.Append(toAlphaNumericChar(nextTwoCharsBits / 45));
                result.Append(toAlphaNumericChar(nextTwoCharsBits % 45));
                count -= 2;
            }
            if (count == 1)
            {
                // special case: one character left
                if (bits.available() < 6)
                {
                    return(false);
                }
                result.Append(toAlphaNumericChar(bits.readBits(6)));
            }

            // See section 6.4.8.1, 6.4.8.2
            if (fc1InEffect)
            {
                // We need to massage the result a bit if in an FNC1 mode:
                for (int i = start; i < result.Length; i++)
                {
                    if (result [i] == '%')
                    {
                        if (i < result.Length - 1 && result [i + 1] == '%')
                        {
                            // %% is rendered as %
                            result.Remove(i + 1, 1);
                        }
                        else
                        {
                            // In alpha mode, % should be converted to FNC1 separator 0x1D
                            result.Remove(i, 1);
                            result.Insert(i, new[] { (char)0x1D });
                        }
                    }
                }
            }

            return(true);
        }
Пример #15
0
        public static void Decompress <T>(T data, BitSource bits, DeflateOutput <T> output)
        {
            while (true)
            {
                using var currentBlock = new DeflateBlock(bits);

                if (currentBlock.Type == BlockType.NoCompression)
                {
                    // skip to next byte
                    bits.SkipToNextByte();

                    // Read length and nlength?
                    var length = bits.ReadBitsAsUshort(16);
                    bits.ConsumeBytes(2);

                    // copy to output
                    output.Write(data, length);
                    bits.ConsumeBytes(length);
                }
                else
                {
                    while (true)
                    {
                        // decode literal/length value from input stream
                        var value = currentBlock.GetNextValue();

                        // end of block
                        if ((value & 0x1FF) == DeflateConstants.EndOfBlock)
                        {
                            break;
                        }

                        if (value < DeflateConstants.EndOfBlock)
                        {
                            //copy value(literal byte) to output stream
                            output.WriteByte((byte)value);
                        }
                        else // value = 257..285
                        {
                            currentBlock.GetLengthAndDistance(value, out var length, out var distance);

                            output.WriteWindow(length, distance);
                        }
                    }
                }

                if (currentBlock.IsFinal)
                {
                    break;
                }
            }
        }
Пример #16
0
        public static DecoderResult decode(sbyte[] bytes)
        {
            BitSource     bits          = new BitSource(bytes);
            StringBuilder result        = new StringBuilder();
            StringBuilder resultTrailer = new StringBuilder(0);

            System.Collections.ArrayList byteSegments = new System.Collections.ArrayList(1);
            int mode = ASCII_ENCODE;

            do
            {
                if (mode == ASCII_ENCODE)
                {
                    mode = decodeAsciiSegment(bits, result, resultTrailer);
                }
                else
                {
                    switch (mode)
                    {
                    case C40_ENCODE:
                        decodeC40Segment(bits, result);
                        break;

                    case TEXT_ENCODE:
                        decodeTextSegment(bits, result);
                        break;

                    case ANSIX12_ENCODE:
                        decodeAnsiX12Segment(bits, result);
                        break;

                    case EDIFACT_ENCODE:
                        decodeEdifactSegment(bits, result);
                        break;

                    case BASE256_ENCODE:
                        decodeBase256Segment(bits, result, byteSegments);
                        break;

                    default:
                        throw new ReaderException();
                    }
                    mode = ASCII_ENCODE;
                }
            } while (mode != PAD_ENCODE && bits.available() > 0);
            if (resultTrailer.Length > 0)
            {
                result.Append(resultTrailer);
            }
            return(new DecoderResult(bytes, result.ToString(), int.Equals(byteSegments.Count, 0) ? null : byteSegments));
        }
Пример #17
0
        internal static System.String decode(sbyte[] bytes, Version version)
        {
            BitSource bits = new BitSource(bytes);

            System.Text.StringBuilder result = new System.Text.StringBuilder();
            Mode mode;

            do
            {
                // While still another segment to read...
                mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
                if (!mode.Equals(Mode.TERMINATOR))
                {
                    // How many characters will follow, encoded in this mode?
                    int count = bits.readBits(mode.getCharacterCountBits(version));
                    if (mode.Equals(Mode.NUMERIC))
                    {
                        decodeNumericSegment(bits, result, count);
                    }
                    else if (mode.Equals(Mode.ALPHANUMERIC))
                    {
                        decodeAlphanumericSegment(bits, result, count);
                    }
                    else if (mode.Equals(Mode.BYTE))
                    {
                        decodeByteSegment(bits, result, count);
                    }
                    else if (mode.Equals(Mode.KANJI))
                    {
                        decodeKanjiSegment(bits, result, count);
                    }
                    else
                    {
                        throw new ReaderException("Unsupported mode indicator");
                    }
                }
            }while (!mode.Equals(Mode.TERMINATOR));

            // I thought it wasn't allowed to leave extra bytes after the terminator but it happens

            /*
             * int bitsLeft = bits.available();
             * if (bitsLeft > 0) {
             * if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) {
             * throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator");
             * }
             * }
             */
            return(result.ToString());
        }
Пример #18
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: static com.google.zxing.common.DecoderResult decode(byte[] bytes) throws com.google.zxing.FormatException
        internal static DecoderResult decode(sbyte[] bytes)
        {
            BitSource       bits          = new BitSource(bytes);
            StringBuilder   result        = new StringBuilder(100);
            StringBuilder   resultTrailer = new StringBuilder(0);
            IList <sbyte[]> byteSegments  = new List <sbyte[]>(1);
            Mode            mode          = Mode.ASCII_ENCODE;

            do
            {
                if (mode == Mode.ASCII_ENCODE)
                {
                    mode = decodeAsciiSegment(bits, result, resultTrailer);
                }
                else
                {
                    switch (mode)
                    {
                    case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.C40_ENCODE:
                        decodeC40Segment(bits, result);
                        break;

                    case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.TEXT_ENCODE:
                        decodeTextSegment(bits, result);
                        break;

                    case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.ANSIX12_ENCODE:
                        decodeAnsiX12Segment(bits, result);
                        break;

                    case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.EDIFACT_ENCODE:
                        decodeEdifactSegment(bits, result);
                        break;

                    case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.BASE256_ENCODE:
                        decodeBase256Segment(bits, result, byteSegments);
                        break;

                    default:
                        throw FormatException.FormatInstance;
                    }
                    mode = Mode.ASCII_ENCODE;
                }
            } while (mode != Mode.PAD_ENCODE && bits.available() > 0);
            if (resultTrailer.Length > 0)
            {
                result.Append(resultTrailer.ToString());
            }
            return(new DecoderResult(bytes, result.ToString(), byteSegments.Count == 0 ? null : byteSegments, null));
        }
 public ulong ReadCompressedLazyFast(bool canBeLong, ref BitSource source)
 {
     if ((source.FinishByte() & 1) > 0)
     {
         return(ReadByte());
     }
     else if (canBeLong)
     {
         return((ulong)ReadInt64());
     }
     else
     {
         return((ulong)ReadInt32());
     }
 }
Пример #20
0
        /// <summary>
        /// See ISO 16022:2006, 5.2.9 and Annex B, B.2
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void decodeBase256Segment(com.google.zxing.common.BitSource bits, StringBuilder result, java.util.Collection<byte[]> byteSegments) throws com.google.zxing.FormatException
        private static void decodeBase256Segment(BitSource bits, StringBuilder result, ICollection <sbyte[]> byteSegments)
        {
            // Figure out how long the Base 256 Segment is.
            int codewordPosition = 1 + bits.ByteOffset;     // position is 1-indexed
            int d1 = unrandomize255State(bits.readBits(8), codewordPosition++);
            int count;

            if (d1 == 0)     // Read the remainder of the symbol
            {
                count = bits.available() / 8;
            }
            else if (d1 < 250)
            {
                count = d1;
            }
            else
            {
                count = 250 * (d1 - 249) + unrandomize255State(bits.readBits(8), codewordPosition++);
            }

            // We're seeing NegativeArraySizeException errors from users.
            if (count < 0)
            {
                throw FormatException.FormatInstance;
            }

            sbyte[] bytes = new sbyte[count];
            for (int i = 0; i < count; i++)
            {
                // Have seen this particular error in the wild, such as at
                // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2
                if (bits.available() < 8)
                {
                    throw FormatException.FormatInstance;
                }
                bytes[i] = (sbyte)unrandomize255State(bits.readBits(8), codewordPosition++);
            }
            byteSegments.Add(bytes);
            try
            {
                //result.Append(new string(bytes, "ISO8859_1"));
                result.Append(GetEncodedStringFromBuffer(bytes, "ISO-8859-1"));
            }
            catch (System.IO.IOException uee)
            {
                throw new InvalidOperationException("Platform does not support required encoding: " + uee);
            }
        }
        public ulong ReadCompressed(bool canBeLong, ref BitSource source)
        {
            if (source.FreeBits == 0)
            {
                source.MoveToNewByte();
            }

            if (Settings.LazyCompressedWriting)
            {
                return(ReadCompressedLazyFast(canBeLong, ref source));
            }
            else
            {
                return(ReadCompressedSlow(ref source));
            }
        }
Пример #22
0
 private static void decodeAlphanumericSegment(BitSource bits, System.Text.StringBuilder result, int count)
 {
     // Read two characters at a time
     while (count > 1)
     {
         int nextTwoCharsBits = bits.readBits(11);
         result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
         result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
         count -= 2;
     }
     if (count == 1)
     {
         // special case: one character left
         result.Append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
     }
 }
Пример #23
0
        /// <summary>
        /// See specification GBT 18284-2000
        /// </summary>
        /// <param name="bits">The bits.</param>
        /// <param name="result">The result.</param>
        /// <param name="count">The count.</param>
        /// <returns></returns>
        private static bool decodeHanziSegment(BitSource bits,
                                               StringBuilder result,
                                               int count)
        {
            // Don't crash trying to read more bits than we have available.
            if (count * 13 > bits.available())
            {
                return(false);
            }

            // Each character will require 2 bytes. Read the characters as 2-byte pairs
            // and decode as GB2312 afterwards
            byte[] buffer = new byte[2 * count];
            int    offset = 0;

            while (count > 0)
            {
                // Each 13 bits encodes a 2-byte character
                int twoBytes          = bits.readBits(13);
                int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
                if (assembledTwoBytes < 0x003BF)
                {
                    // In the 0xA1A1 to 0xAAFE range
                    assembledTwoBytes += 0x0A1A1;
                }
                else
                {
                    // In the 0xB0A1 to 0xFAFE range
                    assembledTwoBytes += 0x0A6A1;
                }
                buffer[offset]     = (byte)((assembledTwoBytes >> 8) & 0xFF);
                buffer[offset + 1] = (byte)(assembledTwoBytes & 0xFF);
                offset            += 2;
                count--;
            }

            try
            {
                result.Append(Encoding.GetEncoding(StringUtils.GB2312).GetString(buffer, 0, buffer.Length));
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
        private static bool decodeKanjiSegment(BitSource bits,
                                               StringBuilder result,
                                               int count)
        {
            // Don't crash trying to read more bits than we have available.
            if (count * 13 > bits.available())
            {
                return(false);
            }

            // Each character will require 2 bytes. Read the characters as 2-byte pairs
            // and decode as Shift_JIS afterwards
            byte[] buffer = new byte[2 * count];
            int    offset = 0;

            while (count > 0)
            {
                // Each 13 bits encodes a 2-byte character
                int twoBytes          = bits.readBits(13);
                int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
                if (assembledTwoBytes < 0x01F00)
                {
                    // In the 0x8140 to 0x9FFC range
                    assembledTwoBytes += 0x08140;
                }
                else
                {
                    // In the 0xE040 to 0xEBBF range
                    assembledTwoBytes += 0x0C140;
                }
                buffer[offset]     = (byte)(assembledTwoBytes >> 8);
                buffer[offset + 1] = (byte)assembledTwoBytes;
                offset            += 2;
                count--;
            }
            // Shift_JIS may not be supported in some environments:
            var encoding = StringUtils.SHIFT_JIS_ENCODING;

            if (encoding == null)
            {
                encoding = StringUtils.PLATFORM_DEFAULT_ENCODING_T;
            }

            result.Append(encoding.GetString(buffer, 0, buffer.Length));

            return(true);
        }
Пример #25
0
        /// <summary>
        /// Возвращает очки за текст
        /// </summary>
        private static int GetPointsForBit(BitSource sourse, PlayerSkills playerSkills)
        {
            switch (sourse)
            {
            case BitSource.Free:
                return(0);

            case BitSource.Self:
                return(2 * playerSkills.BitMaking);

            case BitSource.Bitmaker:
                return(MAX_CATEGORY_POINTS);

            default:
                throw new ArgumentOutOfRangeException(nameof(sourse), sourse, null);
            }
        }
Пример #26
0
        private static bool decodeByteSegment(BitSource bits,
                                              StringBuilder result,
                                              int count,
                                              CharacterSetECI currentCharacterSetECI,
                                              IList byteSegments,
                                              Hashtable hints)
        {
            // Don't crash trying to read more bits than we have available.
            if (count << 3 > bits.available())
            {
                return(false);
            }

            byte[] readBytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (byte)bits.readBits(8);
            }
            String encoding;

            if (currentCharacterSetECI == null)
            {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.
                encoding = StringUtils.guessEncoding(readBytes, hints);
            }
            else
            {
                encoding = currentCharacterSetECI.EncodingName;
            }
            try
            {
                result.Append(Encoding.UTF8.GetChars(readBytes, 0, readBytes.Length));
            }
            catch (Exception)
            {
                return(false);
            }
            byteSegments.Add(readBytes);

            return(true);
        }
        public ulong ReadCompressedSlow(ref BitSource source)
        {
            // Process header
            byte preHeaderCapacity = source.FreeBits;

            (byte noContBytes, byte headerLen) = ReadNoContBytes(ref source);

            byte  bitsToGo = (byte)(8 * noContBytes);
            ulong res      = ReadFirstByteData(ref source, headerLen, bitsToGo, preHeaderCapacity);

            while (bitsToGo > 0)
            {
                bitsToGo -= 8;
                res      |= (ulong)ReadByte() << bitsToGo;
            }

            return(res);
        }
Пример #28
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void decodeKanjiSegment(com.google.zxing.common.BitSource bits, StringBuilder result, int count) throws com.google.zxing.FormatException
        private static void decodeKanjiSegment(BitSource bits, StringBuilder result, int count)
        {
            // Don't crash trying to read more bits than we have available.
            if (count * 13 > bits.available())
            {
                throw FormatException.FormatInstance;
            }

            // Each character will require 2 bytes. Read the characters as 2-byte pairs
            // and decode as Shift_JIS afterwards
            sbyte[] buffer = new sbyte[2 * count];
            int     offset = 0;

            while (count > 0)
            {
                // Each 13 bits encodes a 2-byte character
                int twoBytes          = bits.readBits(13);
                int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
                if (assembledTwoBytes < 0x01F00)
                {
                    // In the 0x8140 to 0x9FFC range
                    assembledTwoBytes += 0x08140;
                }
                else
                {
                    // In the 0xE040 to 0xEBBF range
                    assembledTwoBytes += 0x0C140;
                }
                buffer[offset]     = (sbyte)(assembledTwoBytes >> 8);
                buffer[offset + 1] = (sbyte)assembledTwoBytes;
                offset            += 2;
                count--;
            }
            // Shift_JIS may not be supported in some environments:
            try
            {
                //result.Append(new string(buffer, StringUtils.SHIFT_JIS));
                result.Append(GetEncodedStringFromBuffer(buffer, StringUtils.SHIFT_JIS));
            }
            catch (System.IO.IOException)
            {
                throw FormatException.FormatInstance;
            }
        }
Пример #29
0
        /// <summary>
        /// See specification GBT 18284-2000
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static void decodeHanziSegment(com.google.zxing.common.BitSource bits, StringBuilder result, int count) throws com.google.zxing.FormatException
        private static void decodeHanziSegment(BitSource bits, StringBuilder result, int count)
        {
            // Don't crash trying to read more bits than we have available.
            if (count * 13 > bits.available())
            {
                throw FormatException.FormatInstance;
            }

            // Each character will require 2 bytes. Read the characters as 2-byte pairs
            // and decode as GB2312 afterwards
            sbyte[] buffer = new sbyte[2 * count];
            int     offset = 0;

            while (count > 0)
            {
                // Each 13 bits encodes a 2-byte character
                int twoBytes          = bits.readBits(13);
                int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
                if (assembledTwoBytes < 0x003BF)
                {
                    // In the 0xA1A1 to 0xAAFE range
                    assembledTwoBytes += 0x0A1A1;
                }
                else
                {
                    // In the 0xB0A1 to 0xFAFE range
                    assembledTwoBytes += 0x0A6A1;
                }
                buffer[offset]     = (sbyte)((assembledTwoBytes >> 8) & 0xFF);
                buffer[offset + 1] = (sbyte)(assembledTwoBytes & 0xFF);
                offset            += 2;
                count--;
            }

            try
            {
                //result.Append(new string(buffer,  StringUtils.GB2312));
                result.Append(GetEncodedStringFromBuffer(buffer, StringUtils.GB2312));
            }
            catch (System.IO.IOException)
            {
                throw FormatException.FormatInstance;
            }
        }
        private static bool decodeByteSegment(BitSource bits,
                                              StringBuilder result,
                                              int count,
                                              CharacterSetECI currentCharacterSetECI,
                                              IList <byte[]> byteSegments,
                                              IDictionary <DecodeHintType, object> hints)
        {
            // Don't crash trying to read more bits than we have available.
            if (count << 3 > bits.available())
            {
                return(false);
            }

            byte[] readBytes = new byte[count];
            for (int i = 0; i < count; i++)
            {
                readBytes[i] = (byte)bits.readBits(8);
            }
            Encoding encoding;

            if (currentCharacterSetECI == null)
            {
                // The spec isn't clear on this mode; see
                // section 6.4.5: t does not say which encoding to assuming
                // upon decoding. I have seen ISO-8859-1 used as well as
                // Shift_JIS -- without anything like an ECI designator to
                // give a hint.
                encoding = StringUtils.guessCharset(readBytes, hints);
            }
            else
            {
                encoding = CharacterSetECI.getEncoding(currentCharacterSetECI.EncodingName);
            }
            if (encoding == null)
            {
                encoding = StringUtils.PLATFORM_DEFAULT_ENCODING_T;
            }
            result.Append(encoding.GetString(readBytes, 0, readBytes.Length));

            byteSegments.Add(readBytes);

            return(true);
        }
Пример #31
0
 public void testSource()
 {
    byte[] bytes = {1, 2, 3, 4, 5};
    BitSource source = new BitSource(bytes);
    Assert.AreEqual(40, source.available());
    Assert.AreEqual(0, source.readBits(1));
    Assert.AreEqual(39, source.available());
    Assert.AreEqual(0, source.readBits(6));
    Assert.AreEqual(33, source.available());
    Assert.AreEqual(1, source.readBits(1));
    Assert.AreEqual(32, source.available());
    Assert.AreEqual(2, source.readBits(8));
    Assert.AreEqual(24, source.available());
    Assert.AreEqual(12, source.readBits(10));
    Assert.AreEqual(14, source.available());
    Assert.AreEqual(16, source.readBits(8));
    Assert.AreEqual(6, source.available());
    Assert.AreEqual(5, source.readBits(6));
    Assert.AreEqual(0, source.available());
 }