Example #1
0
        public void BuildCodingTableTest5()
        {
            HuffmanEncoder encoder = new HuffmanEncoder();
            HuffmanTree    tree    = HuffmanTreeHelper.Builder().NewInternalNode(44)
                                     .WithLeft(19, 'C')
                                     .WithRightInternal(25)
                                     .GoToRight()
                                     .WithLeft(11, 'B')
                                     .WithRightInternal(14)
                                     .GoToRight()
                                     .WithRight(9, 'E')
                                     .WithLeftInternal(5)
                                     .GoToLeft()
                                     .WithLeft(2, 'D')
                                     .WithRight(3, 'A')
                                     .CreateTree();

            CodingTable codingTable = encoder.BuildCodingTable(tree);

            Assert.IsNotNull(codingTable);

            Pair <byte, BitSequence>[] expected =
            {
                new Pair <byte, BitSequence>((byte)'A', BitSequence.FromString("1101")),
                new Pair <byte, BitSequence>((byte)'B', BitSequence.FromString("10")),
                new Pair <byte, BitSequence>((byte)'C', BitSequence.FromString("0")),
                new Pair <byte, BitSequence>((byte)'D', BitSequence.FromString("1100")),
                new Pair <byte, BitSequence>((byte)'E', BitSequence.FromString("111")),
            };
            CollectionAssert.AreEquivalent(expected, codingTable);
        }
Example #2
0
        /// <summary>
        /// エンコードされたデータのバイト配列を返します。
        /// </summary>
        public override byte[] GetBytes()
        {
            var bs        = new BitSequence();
            int bitLength = 10;

            for (int i = 0; i <= (_codeWords.Count - 1) - 1; ++i)
            {
                bs.Append(_codeWords[i], bitLength);
            }

            switch (_charCounter % 3)
            {
            case 1:
                bitLength = 4;
                break;

            case 2:
                bitLength = 7;
                break;

            default:
                bitLength = 10;
                break;
            }

            bs.Append(_codeWords[_codeWords.Count - 1], bitLength);

            return(bs.GetBytes());
        }
        /// <summary>
        /// Converts the string representation of an IPv4 address (1.2.3.4) to its IPv4 address equivalent.
        /// A return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="value">A string containing the IPv4 address to convert (1.2.3.4).</param>
        /// <param name="result">
        /// When this method returns, contains the IPv4 address value equivalent of the IPv4 address contained in s, if the conversion succeeded,
        /// or zero IPv4 address if the conversion failed.
        /// The conversion fails if the s parameter is null or String.Empty or is not of the correct format. This parameter is passed uninitialized.
        /// </param>
        /// <returns>True iff parsing was successful.</returns>
        public static bool TryParse(string value, out IpV4Address result)
        {
            if (value == null)
            {
                result = Zero;
                return(false);
            }

            string[] valuesStrings = value.Split('.');
            if (valuesStrings.Length != 4)
            {
                result = Zero;
                return(false);
            }

            byte[] values = new byte[4];
            for (int i = 0; i != 4; ++i)
            {
                if (!byte.TryParse(valuesStrings[i], NumberStyles.None, CultureInfo.InvariantCulture, out values[i]))
                {
                    result = Zero;
                    return(false);
                }
            }

            result = new IpV4Address(BitSequence.Merge(values[0], values[1], values[2], values[3]));
            return(true);
        }
Example #4
0
        private void WriteSegments(BitSequence bs)
        {
            foreach (QRCodeEncoder segment in _segments)
            {
                bs.Append(segment.ModeIndicator, ModeIndicator.LENGTH);
                bs.Append(segment.CharCount,
                          CharCountIndicator.GetLength(
                              _currVersion, segment.EncodingMode)
                          );

                byte[] data = segment.GetBytes();

                for (int i = 0; i < data.Length - 1; ++i)
                {
                    bs.Append(data[i], 8);
                }

                int codewordBitLength = segment.BitCount % 8;

                if (codewordBitLength == 0)
                {
                    codewordBitLength = 8;
                }

                bs.Append(data[data.Length - 1] >> (8 - codewordBitLength),
                          codewordBitLength);
            }
        }
Example #5
0
 private void WritePaddingBits(BitSequence bs)
 {
     if (bs.Length % 8 > 0)
     {
         bs.Append(0x0, 8 - (bs.Length % 8));
     }
 }
Example #6
0
    public void AppendByteWorks()
    {
      var bits = new BitSequence();
      var bytes = new Dictionary<byte, bool[]>()
      {
        { 0, new[] { false, false, false, false, false, false, false, false } },
        { 1, new[] { true, false, false, false, false, false, false, false } },
        { 7, new[] { true, true, true, false, false, false, false, false } },
        { 8, new[] { false, false, false, true, false, false, false, false } },
        { 77, new[] { true, false, true, true, false, false, true, false } },
        { 127, new[] { true, true, true, true, true, true, true, false } },
        { 128, new[] { false, false, false, false, false, false, false, true } },
        { 196, new[] { false, false, true, false, false, false, true, true } },
        { 255, new[] { true, true, true, true, true, true, true, true } },
      };

      foreach (var @byte in bytes.Keys)
      {
        bits.AppendByte(@byte);
      }

      var actual = bits.ToBitArray();
      var expected = bytes.Values.SelectMany(v => v).ToArray();
      CollectionAssert.AreEqual(actual, expected);
    }
 public void EqualsSimpleTest()
 {
     sequence = new BitSequence();
     Assert.IsFalse(sequence.Equals(null));
     Assert.IsTrue(sequence.Equals(sequence));
     Assert.IsTrue(sequence.Equals(new BitSequence()));
 }
Example #8
0
        private void WriteTerminator(BitSequence bs)
        {
            int terminatorLength = Math.Min(
                ModeIndicator.LENGTH, _dataBitCapacity - _dataBitCounter);

            bs.Append(ModeIndicator.TERMINATOR_VALUE, terminatorLength);
        }
Example #9
0
        public static string Decode(byte[] data)
        {
            using var ms = new MemoryStream(data);
            int dictLen = ms.ReadByte(); // ilość znaków
            var dict    = new Dictionary <BitSequence, char>();

            // odczytanie słownika
            for (int i = 0; i < dictLen; i++)
            {
                char        c      = (char)ms.ReadByte();     // znak
                int         seqLen = ms.ReadByte();           // długośc znaku
                BitSequence seq    = new BitSequence(seqLen); // kod
                ms.Read(seq.rawData, 0, seq.ByteCapacity);
                seq.PushLength(seqLen);                       // odczytanie kodu
                dict[seq] = c;                                // dodanie do słownika
            }

            int padding = ms.ReadByte(); // margines

            int encodedLen = ms.Capacity - (int)ms.Position;

            byte[] encoded = new byte[encodedLen];
            ms.Read(encoded, 0, encodedLen);
            string decoded = Decode(encoded, padding, dict); // odkowowanie

            return(decoded);
        }
Example #10
0
        public void BuildCodingTableTest4()
        {
            HuffmanEncoder encoder = new HuffmanEncoder();
            HuffmanTree    tree    = HuffmanTreeHelper.Builder().NewInternalNode(133)
                                     .WithRight(85, 'f')
                                     .WithLeftInternal(48)
                                     .GoToLeft()
                                     .WithLeftInternal(21)
                                     .WithRightInternal(27)
                                     .GoToRight()
                                     .WithLeft(13, 'd')
                                     .WithRight(14, 'e')
                                     .GoToSibling()
                                     .WithRight(12, 'a')
                                     .WithLeftInternal(9)
                                     .GoToLeft()
                                     .WithRight(7, 'c')
                                     .WithLeft(2, 'b')
                                     .CreateTree();

            CodingTable codingTable = encoder.BuildCodingTable(tree);

            Assert.IsNotNull(codingTable);

            Pair <byte, BitSequence>[] expected =
            {
                new Pair <byte, BitSequence>((byte)'a', BitSequence.FromString("001")),
                new Pair <byte, BitSequence>((byte)'b', BitSequence.FromString("0000")),
                new Pair <byte, BitSequence>((byte)'c', BitSequence.FromString("0001")),
                new Pair <byte, BitSequence>((byte)'d', BitSequence.FromString("010")),
                new Pair <byte, BitSequence>((byte)'e', BitSequence.FromString("011")),
                new Pair <byte, BitSequence>((byte)'f', BitSequence.FromString("1")),
            };
            CollectionAssert.AreEquivalent(expected, codingTable);
        }
Example #11
0
        /// <summary>
        /// 1bppビットマップファイルのバイトデータを返します。
        /// </summary>
        /// <param name="moduleSize">モジュールサイズ(px)</param>
        /// <param name="foreRgb">前景色</param>
        /// <param name="backRgb">背景色</param>
        private byte[] GetBitmap1bpp(int moduleSize, string foreRgb, string backRgb)
        {
            Color foreColor = ColorTranslator.FromHtml(foreRgb);
            Color backColor = ColorTranslator.FromHtml(backRgb);

            int[][] moduleMatrix = QuietZone.Place(GetModuleMatrix());

            int width, height;

            width = height = moduleSize * moduleMatrix.Length;

            int rowBytesLen = (width + 7) / 8;

            int pack8bit = 0;

            if (width % 8 > 0)
            {
                pack8bit = 8 - (width % 8);
            }

            int pack32bit = 0;

            if (rowBytesLen % 4 > 0)
            {
                pack32bit = 8 * (4 - (rowBytesLen % 4));
            }

            int rowSize = (width + pack8bit + pack32bit) / 8;

            byte[] bitmapData = new byte[rowSize * height];
            int    offset     = 0;

            for (int r = moduleMatrix.Length - 1; r >= 0; --r)
            {
                var bs = new BitSequence();

                foreach (int v in moduleMatrix[r])
                {
                    int color = Values.IsDark(v) ? 0 : 1;

                    for (int i = 1; i <= moduleSize; ++i)
                    {
                        bs.Append(color, 1);
                    }
                }
                bs.Append(0, pack8bit);
                bs.Append(0, pack32bit);

                byte[] bitmapRow = bs.GetBytes();

                for (int i = 1; i <= moduleSize; ++i)
                {
                    Array.Copy(bitmapRow, 0, bitmapData, offset, rowSize);
                    offset += rowSize;
                }
            }

            return(DIB.Build1bppDIB(bitmapData, width, height, foreColor, backColor));
        }
Example #12
0
    public void AppendOffBitWorks()
    {
      var bits = new BitSequence();

      bits.AppendBit(false);
      bits.AppendOffBit();
      CollectionAssert.AreEqual(new[] { false, false }, bits.ToBitArray());
    }
Example #13
0
    public void AppendOnBitWorks()
    {
      var bits = new BitSequence();

      bits.AppendBit(true);
      bits.AppendOnBit();
      CollectionAssert.AreEqual(new[] { true, true }, bits.ToBitArray());
    }
Example #14
0
 public static Double HEXtoF64(Byte[] src, BitSequence seq = BitSequence.LittleEndian)
 {
     if (src.Length != 8)
     { throw new ArgumentOutOfRangeException("LibHex.Core.HexTools.HEXtoF64 : Source array must contain 8 elements."); }
     MidDouble m = MidDouble.Init();
     m.intValue = HEXtoU64(src, seq);
     return m.doubleValue;
 }
Example #15
0
 /// <summary>
 /// A hash code out of the combination of the authentication prohibited, confidentiality prohibited, experimental, user associated, IPSec, email,
 /// name type, signatory, protocol, algorithm, flags extension and public key fields.
 /// </summary>
 public override int GetHashCode()
 {
     return(Sequence.GetHashCode(
                BitSequence.Merge(BitSequence.Merge(AuthenticationProhibited, ConfidentialityProhibited, Experimental, UserAssociated, IpSec, Email),
                                  (byte)NameType, (byte)Signatory, (byte)Protocol),
                BitSequence.Merge((byte)Algorithm, (ushort)(FlagsExtension.HasValue ? FlagsExtension.Value : 0)),
                PublicKey));
 }
 static void AssertSequence(BitSequence sequence, params int[] bits)
 {
     int[] actual = new int[sequence.Size];
     for (int n = 0; n < sequence.Size; n++)
     {
         actual[n] = sequence[n] == Bit.Zero ? 0 : 1;
     }
     CollectionAssert.AreEqual(bits, actual);
 }
Example #17
0
    public void AppendBitsWorks()
    {
      var bits = new BitSequence();

      bits.AppendBits(true, false, true, false);
      bits.AppendBits(Enumerable.Range(0, 4).Select(i => i % 2 == 1));

      CollectionAssert.AreEqual(new[] { true, false, true, false, false, true, false, true }, bits.ToBitArray());
    }
 public IpV4Address(string value)
 {
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     string[] strArray = value.Split('.');
     this._value = BitSequence.Merge(byte.Parse(strArray[0], (IFormatProvider)CultureInfo.InvariantCulture), byte.Parse(strArray[1], (IFormatProvider)CultureInfo.InvariantCulture), byte.Parse(strArray[2], (IFormatProvider)CultureInfo.InvariantCulture), byte.Parse(strArray[3], (IFormatProvider)CultureInfo.InvariantCulture));
 }
Example #19
0
 /// <summary>
 /// Returns a hash code for the layer.
 /// The hash code is a XOR of a combination of the protocol type and operation and the hash codes of the layer length and data link.
 /// </summary>
 public override int GetHashCode()
 {
     return(base.GetHashCode() ^
            BitSequence.Merge((ushort)ProtocolType, (ushort)Operation).GetHashCode() ^
            SenderHardwareAddress.BytesSequenceGetHashCode() ^
            SenderProtocolAddress.BytesSequenceGetHashCode() ^
            TargetHardwareAddress.BytesSequenceGetHashCode() ^
            TargetProtocolAddress.BytesSequenceGetHashCode());
 }
Example #20
0
        private static (byte[] encoded, int padding) Encode(string text, Dictionary <char, BitSequence> dictionary)
        {
            BitSequence sequence = new BitSequence(8 * text.Length);

            foreach (char c in text)          // pętla przez każdy znak tekstu
            {
                sequence.Push(dictionary[c]); // dodaje do sekwencji bitów kod odpowiadajacy znakowi
            }
            return(sequence.GetBytes());
        }
Example #21
0
    public void AppendBitWorks()
    {
      var bits = new BitSequence();

      bits.AppendBit(true);
      Assert.IsTrue(bits.Pop());

      bits.AppendBit(false);
      Assert.IsFalse(bits.Pop());
    }
        public void CloneTest2()
        {
            sequence[0]  = Bit.One;
            sequence[3]  = Bit.One;
            sequence[5]  = Bit.Zero;
            sequence[11] = Bit.One;
            BitSequence clonedSequence = sequence.Clone();

            Assert.AreEqual(12, clonedSequence.Size);
            AssertSequence(clonedSequence, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1);
        }
Example #23
0
        public void EqualityTest()
        {
            var seq1 = new BitSequence(16);
            var seq2 = new BitSequence(16);

            seq1.Push(true);
            seq1.Push(true);
            seq2.Push(seq1);
            Assert.Equal(seq1, seq2);
            Assert.Equal(seq1.GetHashCode(), seq2.GetHashCode());
        }
Example #24
0
        /// <summary>
        /// エンコードされたデータのバイト配列を返します。
        /// </summary>
        public override byte[] GetBytes()
        {
            var bs = new BitSequence();

            foreach (int wd in _codeWords)
            {
                bs.Append(wd, 13);
            }

            return(bs.GetBytes());
        }
Example #25
0
 private void WriteStructuredAppendHeader(BitSequence bs)
 {
     bs.Append(ModeIndicator.STRUCTURED_APPEND_VALUE,
               ModeIndicator.LENGTH);
     bs.Append(_position,
               SymbolSequenceIndicator.POSITION_LENGTH);
     bs.Append(_parent.Count - 1,
               SymbolSequenceIndicator.TOTAL_NUMBER_LENGTH);
     bs.Append(_parent.Parity,
               StructuredAppend.PARITY_DATA_LENGTH);
 }
Example #26
0
        public void KeysTest()
        {
            Dictionary <BitSequence, char> dict = new Dictionary <BitSequence, char>();
            var seq1 = new BitSequence(16);
            var seq2 = new BitSequence(16);

            seq1.Push(true);
            seq1.Push(true);
            seq2.Push(seq1);
            dict[seq1] = 'c';
            Assert.True(dict.ContainsKey(seq2));
        }
Example #27
0
        public static Byte[] ToBinary(this UInt16 src, BitSequence seq = BitSequence.LittleEndian)
        {
            Byte[] result = new Byte[2];
            result[1] = Convert.ToByte(src & 0xFF);
            result[0] = Convert.ToByte((src >> 8) & 0xFF);

            if (seq == BitSequence.LittleEndian)
            {
                Array.Reverse(result);
            }
            return result;
        }
Example #28
0
        public void ToStringTest()
        {
            var seq = new BitSequence(16);

            seq.Push();
            seq.Push(true);
            seq.Push(false);
            seq.Push(true);
            seq.Push(true);
            seq.Push(false);
            Assert.Equal("010110", seq.ToString());
        }
Example #29
0
 public MacAddress(string address)
 {
     if (address == null)
     {
         throw new ArgumentNullException("address");
     }
     string[] strArray = address.Split(':');
     if (strArray.Length != 6)
     {
         throw new ArgumentException("Failed parsing " + (object)address + " as mac address. Expected 6 hexes and got " + (string)(object)strArray.Length + " hexes", "address");
     }
     this._value = BitSequence.Merge(Convert.ToByte(strArray[0], 16), Convert.ToByte(strArray[1], 16), Convert.ToByte(strArray[2], 16), Convert.ToByte(strArray[3], 16), Convert.ToByte(strArray[4], 16), Convert.ToByte(strArray[5], 16));
 }
        /// <summary>
        /// Creates an address from an address string (1.2.3.4).
        /// </summary>
        public IpV4Address(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            string[] values = value.Split('.');
            _value = BitSequence.Merge(byte.Parse(values[0], CultureInfo.InvariantCulture),
                                       byte.Parse(values[1], CultureInfo.InvariantCulture),
                                       byte.Parse(values[2], CultureInfo.InvariantCulture),
                                       byte.Parse(values[3], CultureInfo.InvariantCulture));
        }
Example #31
0
        private void WritePadCodewords(BitSequence bs)
        {
            int numDataCodewords = DataCodeword.GetTotalNumber(
                _parent.ErrorCorrectionLevel, _currVersion);

            bool flag = true;

            while (bs.Length < 8 * numDataCodewords)
            {
                bs.Append(flag ? 236 : 17, 8);
                flag = !flag;
            }
        }
Example #32
0
        public void IndexerGetterTest()
        {
            var seq = new BitSequence(16);

            seq.rawData = new byte[] { 3, 5 };
            Assert.False(seq[0]);
            Assert.True(seq[6]);
            Assert.True(seq[7]);
            Assert.False(seq[8]);
            Assert.False(seq[9]);
            Assert.True(seq[13]);
            Assert.True(seq[15]);
            Assert.Throws <ArgumentOutOfRangeException>(() => seq[16]);
        }
Example #33
0
        public void BuildCodingTableTest2()
        {
            HuffmanEncoder encoder     = new HuffmanEncoder();
            HuffmanTree    tree        = HuffmanTreeHelper.Builder().NewNode(1, 'X').CreateTree();
            CodingTable    codingTable = encoder.BuildCodingTable(tree);

            Assert.IsNotNull(codingTable);

            Pair <byte, BitSequence>[] expected =
            {
                new Pair <byte, BitSequence>((byte)'X', BitSequence.FromString("0"))
            };
            CollectionAssert.AreEquivalent(expected, codingTable);
        }
Example #34
0
    public static StunMessageAttribute Parse(BitSequence bits)
    {
      var type = (StunMessageAttributeType)(BitConverter.ToUInt16(bits.PopLittleEndianBytes(2), 0));
      var length = BitConverter.ToUInt16(bits.PopLittleEndianBytes(2), 0);

      switch (type)
      {
        case StunMessageAttributeType.XorMappedAddress:
          {
            return ParseXorMappedAddress(bits);
          }
      }

      throw new InvalidOperationException("Invalid attribute.");
    }
Example #35
0
        public void PushSequenceTest()
        {
            var seq1 = new BitSequence(16);
            var seq2 = new BitSequence(8);

            seq1.Push();
            seq1.Push(true);
            seq2.Push();
            seq2.Push(true);
            seq2.Push(true);
            seq2.Push(true);
            seq1.Push(seq2);
            Assert.Equal("010111", seq1.ToString());
            Assert.Equal(6, seq1.Length);
        }
        /// <summary>
        ///     Get the value from the dehydrated data which is always in the last byte
        /// </summary>
        /// <param name="data"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private static byte GetVersion(IByteArray data, int offset, int length)
        {
            if ((data == null) || data.IsEmpty)
            {
                return(CURRENT_DEFAULT_VERSION);
            }

            var slice = data.Span.Slice(offset, length);

            //always the last byte
            byte entry = slice[slice.Length - 1];

            BitSequence sequence = new BitSequence(entry, DataDehydrator.entries);

            return((byte)sequence.GetEntryValue(0));
        }
        /// <summary>
        /// Create the address from a string in the format XX:XX:XX:XX:XX:XX.
        /// </summary>
        /// <param name="address">The string value in hexadecimal format. Every two digits are separated by a colon.</param>
        public MacAddress(string address)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            string[] hexes = address.Split(':');
            if (hexes.Length != 6)
            {
                throw new ArgumentException("Failed parsing " + address + " as mac address. Expected 6 hexes and got " + hexes.Length + " hexes", "address");
            }

            _value = BitSequence.Merge(Convert.ToByte(hexes[0], 16), Convert.ToByte(hexes[1], 16), Convert.ToByte(hexes[2], 16),
                                       Convert.ToByte(hexes[3], 16), Convert.ToByte(hexes[4], 16), Convert.ToByte(hexes[5], 16));
        }
Example #38
0
        /// <summary>
        /// コード語に変換するメッセージビット列を返します。
        /// </summary>
        private byte[] GetMessageBytes()
        {
            var bs = new BitSequence();

            if (_parent.Count > 1)
            {
                WriteStructuredAppendHeader(bs);
            }

            WriteSegments(bs);
            WriteTerminator(bs);
            WritePaddingBits(bs);
            WritePadCodewords(bs);

            return(bs.GetBytes());
        }
Example #39
0
 public static Byte[] ToBinary(this Double src, BitSequence seq = BitSequence.LittleEndian)
 {
     MidDouble m = MidDouble.Init();
     m.doubleValue = src;
     return m.intValue.ToBinary(seq);
 }
Example #40
0
        public static UInt64 HEXtoU64(Byte[] src, BitSequence seq = BitSequence.LittleEndian)
        {
            if (src.Length != 8)
            { throw new ArgumentOutOfRangeException("LibHex.Core.HexTools.HEXtoU64 : Source array must contain 8 elements."); }
            if (seq == BitSequence.LittleEndian) { Array.Reverse(src); }

            UInt64 result = src[7];
            for (int i = 1; i < 8; i++)
            { result |= Convert.ToUInt64(Convert.ToUInt64(src[7 - i]) << (i * 8)); }

            return result;
        }
Example #41
0
 public static Byte[] I16toHEX(Int16 src, BitSequence seq = BitSequence.LittleEndian)
 {
     return U16toHEX((UInt16)src, seq);
 }
Example #42
0
 public void WriteLong(Int64 b, BitSequence seq = BitSequence.LittleEndian)
 {
     Write(HexTools.I64toHEX(b, seq), 0, 8);
 }
Example #43
0
        public static Byte[] ToBinary(this UInt32 src, BitSequence seq = BitSequence.LittleEndian)
        {
            Byte[] result = new Byte[4];
            for (int i = 0; i < 4; i++)
            {
                result[3 - i] = Convert.ToByte(src & 0xFF);
                src >>= 8;
            }

            if (seq == BitSequence.LittleEndian)
            {
                Array.Reverse(result);
            }
            return result;
        }
Example #44
0
        //Hexadecimal -> Decimal
        public static UInt16 HEXtoU16(Byte[] src, BitSequence seq = BitSequence.LittleEndian)
        {
            if (src.Length != 2)
            { throw new ArgumentOutOfRangeException("LibHex.Core.HexTools.HEXtoU16 : Source array must contain 2 elements."); }
            if (seq == BitSequence.LittleEndian) { Array.Reverse(src); }

            UInt16 result = src[1];
            result |= Convert.ToUInt16(Convert.ToUInt16(src[0]) << 8);

            return result;
        }
Example #45
0
        public static UInt16 ToUInt16(this Byte[] src, Int32 offset, BitSequence seq = BitSequence.LittleEndian)
        {
            if (offset < 0 || offset > src.Length - 2)
                throw new ArgumentOutOfRangeException("offset", "Byte[].ToUInt16(): Offset out of source array bounds");

            UInt16 result;
            if (seq == BitSequence.LittleEndian)
            {
                result = src[0];
                result |= Convert.ToUInt16(Convert.ToUInt16(src[1]) << 8);
            }
            else
            {
                result = src[1];
                result |= Convert.ToUInt16(Convert.ToUInt16(src[0]) << 8);
            }

            return result;
        }
Example #46
0
 public static Int32 HEXtoI32(Byte[] src, BitSequence seq = BitSequence.LittleEndian)
 {
     if (src.Length != 4)
     { throw new ArgumentOutOfRangeException("LibHex.Core.HexTools.HEXtoI32 : Source array must contain 4 elements."); }
     return Sign(HEXtoU32(src, seq));
 }
Example #47
0
 public Int64 ReadLong(BitSequence seq = BitSequence.LittleEndian)
 {
     return HexTools.HEXtoI64(ReadBytes(8), seq);
 }
Example #48
0
 public UInt32 ReadUInt(BitSequence seq = BitSequence.LittleEndian)
 {
     return HexTools.HEXtoU32(ReadBytes(4), seq);
 }
Example #49
0
 public UInt64 ReadULong(BitSequence seq = BitSequence.LittleEndian)
 {
     return HexTools.HEXtoU64(ReadBytes(8), BitSequence.LittleEndian);
 }
Example #50
0
 public UInt16 ReadUShort(BitSequence seq = BitSequence.LittleEndian)
 {
     return HexTools.HEXtoU16(ReadBytes(2), seq);
 }
Example #51
0
 public void WriteInt(Int32 b, BitSequence seq = BitSequence.LittleEndian)
 {
     Write(HexTools.I32toHEX(b, seq), 0, 4);
 }
Example #52
0
        public static Int64 ToInt64(this Byte[] src, Int32 offset, BitSequence seq = BitSequence.LittleEndian)
        {
            if (offset < 0 || offset > src.Length - 8)
                throw new ArgumentOutOfRangeException("offset", "Byte[].ToInt64(): Offset out of source array bounds");

            return Sign(src.ToUInt64(offset, seq));
        }
Example #53
0
        public static Single ToSingle(this Byte[] src, Int32 offset, BitSequence seq = BitSequence.LittleEndian)
        {
            if (offset < 0 || offset > src.Length - 4)
                throw new ArgumentOutOfRangeException("offset", "Byte[].ToSingle(): Offset out of source array bounds");

            MidSingle m = MidSingle.Init();
            m.intValue = src.ToUInt32(offset, seq);
            return m.singleValue;
        }
Example #54
0
 public static Byte[] F64toHEX(Double src, BitSequence seq = BitSequence.LittleEndian)
 {
     MidDouble m = MidDouble.Init();
     m.doubleValue = src;
     return U64toHEX(m.intValue, seq);
 }
Example #55
0
        public static UInt64 ToUInt64(this Byte[] src, Int32 offset, BitSequence seq = BitSequence.LittleEndian)
        {
            if (offset < 0 || offset > src.Length - 8)
                throw new ArgumentOutOfRangeException("offset", "Byte[].ToUInt64(): Offset out of source array bounds");

            UInt64 result;
            if (seq == BitSequence.LittleEndian)
            {
                result = src[0];
                for (int i = 1; i < 8; i++)
                {
                    result |= Convert.ToUInt64(Convert.ToUInt64(src[i]) << (i * 8));
                }
            }
            else
            {
                result = src[7];
                for (int i = 1; i < 8; i++)
                {
                    result |= Convert.ToUInt64(Convert.ToUInt64(src[7 - i]) << (i * 8));
                }
            }

            return result;
        }
Example #56
0
 public static Byte[] F32toHEX(Single src, BitSequence seq = BitSequence.LittleEndian)
 {
     MidSingle m = MidSingle.Init();
     m.singleValue = src;
     return U32toHEX(m.intValue, seq);
 }
Example #57
0
 public static Byte[] ToBinary(this Int16 src, BitSequence seq = BitSequence.LittleEndian)
 {
     return Unsign(src).ToBinary(seq);
 }
Example #58
0
        public static Byte[] U64toHEX(UInt64 src, BitSequence seq = BitSequence.LittleEndian)
        {
            Byte[] result = new Byte[8];
            for (int i = 0; i < 8; i++)
            { result[7 - i] = Convert.ToByte(src & 0xFF); src >>= 8; }

            if (seq == BitSequence.LittleEndian)
            { Array.Reverse(result); }
            return result;
        }
Example #59
0
 public static Byte[] I64toHEX(Int64 src, BitSequence seq = BitSequence.LittleEndian)
 {
     return U64toHEX(Unsign(src), seq);
 }
Example #60
0
 public void WriteShort(Int16 b, BitSequence seq = BitSequence.LittleEndian)
 {
     Write(HexTools.I16toHEX(b, seq), 0, 2);
 }