/// <summary>
    /// Constructs a new binary reader with the given bit converter, reading
    /// to the given stream, using the given encoding.
    /// </summary>
    /// <param name="bitConverter">Converter to use when reading data</param>
    /// <param name="stream">Stream to read data from</param>
    /// <param name="encoding">Encoding to use when reading character data</param>
    public EndianBinaryReader(EndianBitConverter bitConverter, Stream stream, Encoding encoding)
    {
        if (bitConverter == null)
            {
                throw new ArgumentNullException("bitConverter");
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }
            if (!stream.CanRead)
            {
                throw new ArgumentException("Stream isn't writable", "stream");
            }
            this.stream = stream;
            this.bitConverter = bitConverter;
            this.encoding = encoding;
            this.decoder = encoding.GetDecoder();
            this.minBytesPerChar = 1;

            if (encoding is UnicodeEncoding)
            {
                minBytesPerChar = 2;
            }
    }
示例#2
0
        /// <summary>
        ///     Constructs a new binary reader with the given bit converter, reading
        ///     to the given stream, using the given encoding.
        /// </summary>
        /// <param name="bitConverter">Converter to use when reading data</param>
        /// <param name="stream">Stream to read data from</param>
        /// <param name="encoding">Encoding to use when reading character data</param>
        public EndianBinaryReader(EndianBitConverter bitConverter, Stream stream, Encoding encoding)
        {
            if (bitConverter == null)
            {
                throw new ArgumentNullException(nameof(bitConverter));
            }
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }
            if (!stream.CanRead)
            {
                throw new ArgumentException("Stream isn't writable", nameof(stream));
            }
            BaseStream = stream;
            BitConverter = bitConverter;
            Encoding = encoding;
            decoder = encoding.GetDecoder();
            minBytesPerChar = 1;

            if (encoding is UnicodeEncoding)
            {
                minBytesPerChar = 2;
            }
        }
        public static void DecryptSngData(Stream input, Stream output, byte[] key, EndianBitConverter conv)
        {
            var reader = new EndianBinaryReader(conv, input);

            if (0x4A != reader.ReadUInt32())
            {
                throw new InvalidDataException("This is not valid SNG file to decrypt.");
            }
            reader.ReadBytes(4);//platform header (bitfield? 001 - Compressed; 010 - Encrypted;)
            byte[] iv = reader.ReadBytes(16);
            using (var rij = new RijndaelManaged())
            {
                InitRijndael(rij, key, CipherMode.CFB);
                rij.IV = iv;

                var  buffer = new byte[16];
                long len    = input.Length - input.Position;
                for (long i = 0; i < len; i += buffer.Length)
                {
                    using (ICryptoTransform transform = rij.CreateDecryptor())
                    {
                        var cs        = new CryptoStream(output, transform, CryptoStreamMode.Write);
                        int bytesread = input.Read(buffer, 0, buffer.Length);
                        cs.Write(buffer, 0, bytesread);

                        int pad = buffer.Length - bytesread;
                        if (pad > 0)
                        {
                            cs.Write(new byte[pad], 0, pad);
                        }

                        cs.Flush();
                    }

                    int  j;
                    bool carry;
                    for (j = (rij.IV.Length) - 1, carry = true; j >= 0 && carry; j--)
                    {
                        carry = ((iv[j] = (byte)(rij.IV[j] + 1)) == 0);
                    }
                    rij.IV = iv;
                }
                output.SetLength(input.Length - (iv.Length + 8));
            }
            output.Flush();
            output.Seek(0, SeekOrigin.Begin);
        }
        /// <summary>
        /// Constructs a new binary writer with the given bit converter, writing
        /// to the given stream, using the given encoding.
        /// </summary>
        /// <param name="bitConverter">Converter to use when writing data</param>
        /// <param name="stream">Stream to write data to</param>
        /// <param name="encoding">Encoding to use when writing character data</param>
        public EndianBinaryWriter(EndianBitConverter bitConverter, Stream stream, Encoding encoding)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!stream.CanWrite)
            {
                throw new ArgumentException("Stream isn't writable", nameof(stream));
            }


            BaseStream   = stream;
            BitConverter = bitConverter ?? throw new ArgumentNullException(nameof(bitConverter));
            Encoding     = encoding ?? throw new ArgumentNullException(nameof(encoding));
        }
示例#5
0
        /// <summary>
        /// Converts the Well-known Binary (WKB) to a polygon.
        /// </summary>
        /// <param name="geometryBytes">The WKB representation of the polygon.</param>
        /// <param name="byteOrder">The byte-order of the conversion.</param>
        /// <param name="dimension">The dimension of the geometry.</param>
        /// <param name="factory">The geometry factory.</param>
        /// <returns>The converted polygon.</returns>
        private static IPolygon ToPolygon(Byte[] geometryBytes, ByteOrder byteOrder, Int32 dimension, IGeometryFactory factory)
        {
            Int32 coordinateSize       = (dimension == 3) ? 24 : 16;
            Int32 ringCount            = EndianBitConverter.ToInt32(geometryBytes, 5, byteOrder);
            Int32 shellCoordinateCount = EndianBitConverter.ToInt32(geometryBytes, 9, byteOrder);

            Coordinate[] shellCoordinates = new Coordinate[shellCoordinateCount];

            for (Int32 byteIndex = 13, coordinateIndex = 0; coordinateIndex < shellCoordinateCount; byteIndex += coordinateSize, coordinateIndex++)
            {
                shellCoordinates[coordinateIndex] = new Coordinate(EndianBitConverter.ToDouble(geometryBytes, byteIndex, byteOrder),
                                                                   EndianBitConverter.ToDouble(geometryBytes, byteIndex + 8, byteOrder),
                                                                   dimension == 3 ? EndianBitConverter.ToDouble(geometryBytes, byteIndex + 16, byteOrder) : 0);
            }

            if (ringCount > 1)
            {
                Coordinate[][] holes = new Coordinate[ringCount - 1][];

                Int32 holeStartIndex = 13 + shellCoordinateCount * coordinateSize;

                for (Int32 ringIndex = 1; ringIndex < ringCount; ringIndex++)
                {
                    Int32 holeCoordianteCount = EndianBitConverter.ToInt32(geometryBytes, holeStartIndex, byteOrder);
                    holeStartIndex += 4;
                    Coordinate[] holeCoordinates = new Coordinate[holeCoordianteCount];

                    for (Int32 byteIndex = holeStartIndex, coordinateIndex = 0; coordinateIndex < holeCoordianteCount; byteIndex += coordinateSize, coordinateIndex++)
                    {
                        holeCoordinates[coordinateIndex] = new Coordinate(EndianBitConverter.ToDouble(geometryBytes, byteIndex, byteOrder),
                                                                          EndianBitConverter.ToDouble(geometryBytes, byteIndex + 8, byteOrder),
                                                                          dimension == 3 ? EndianBitConverter.ToDouble(geometryBytes, byteIndex + 16, byteOrder) : 0);
                    }

                    holes[ringIndex - 1] = holeCoordinates;

                    holeStartIndex += holeCoordianteCount * coordinateSize;
                }

                return(factory.CreatePolygon(shellCoordinates, holes));
            }
            else
            {
                return(factory.CreatePolygon(shellCoordinates));
            }
        }
        /// <summary>
        /// Computes the <see cref="IPolygon" /> representation of the WKB.
        /// </summary>
        /// <param name="geometryBytes">The WKB representation of the geometry.</param>
        /// <param name="byteOrder">The byte-order of the conversion.</param>
        /// <param name="geometryModel">The geometry model of the conversion.</param>
        /// <param name="factory">The factory used for geometry production.</param>
        /// <returns>The <see cref="IPolygon" /> representation of the geometry.</returns>
        private static IPolygon ComputePolygon(Byte[] geometryBytes, ByteOrder byteOrder, GeometryModel geometryModel, IGeometryFactory factory)
        {
            Int32 coordinateSize       = (geometryModel == GeometryModel.Spatial3D) ? 24 : 16;
            Int32 ringCount            = EndianBitConverter.ToInt32(geometryBytes, 5, byteOrder);
            Int32 shellCoordinateCount = EndianBitConverter.ToInt32(geometryBytes, 9, byteOrder);

            Coordinate[] shellCoordinates = new Coordinate[shellCoordinateCount];

            for (Int32 byteIndex = 13, coordinateIndex = 0; coordinateIndex < shellCoordinateCount; byteIndex += coordinateSize, coordinateIndex++)
            {
                shellCoordinates[coordinateIndex] = new Coordinate(EndianBitConverter.ToDouble(geometryBytes, byteIndex, byteOrder),
                                                                   EndianBitConverter.ToDouble(geometryBytes, byteIndex + 8, byteOrder),
                                                                   geometryModel == GeometryModel.Spatial3D ? EndianBitConverter.ToDouble(geometryBytes, byteIndex + 16, byteOrder) : 0);
            }

            if (ringCount > 1)
            {
                Coordinate[][] holes = new Coordinate[ringCount - 1][];

                Int32 holeStartIndex = 13 + shellCoordinateCount * coordinateSize;

                for (Int32 i = 1; i < ringCount; i++)
                {
                    Int32 holeCoordianteCount = EndianBitConverter.ToInt32(geometryBytes, holeStartIndex, byteOrder);
                    holeStartIndex += 4;
                    Coordinate[] holeCoordinates = new Coordinate[holeCoordianteCount];

                    for (Int32 byteIndex = holeStartIndex, coordinateIndex = 0; coordinateIndex < holeCoordianteCount; byteIndex += coordinateSize, coordinateIndex++)
                    {
                        holeCoordinates[coordinateIndex] = new Coordinate(EndianBitConverter.ToDouble(geometryBytes, byteIndex, byteOrder),
                                                                          EndianBitConverter.ToDouble(geometryBytes, byteIndex + 8, byteOrder),
                                                                          geometryModel == GeometryModel.Spatial3D ? EndianBitConverter.ToDouble(geometryBytes, byteIndex + 16, byteOrder) : 0);
                    }

                    holes[i - 1] = holeCoordinates;

                    holeStartIndex += holeCoordianteCount * coordinateSize;
                }

                return(factory.CreatePolygon(shellCoordinates, holes));
            }
            else
            {
                return(factory.CreatePolygon(shellCoordinates));
            }
        }
示例#7
0
        public void UInt64BeTest()
        {
            var buffer = new byte[512];
            var random = new Random(nameof(UInt64BeTest).Sum(c => c));

            for (int i = 0; i < 1000; i++)
            {
                var expected = (((ulong)random.Next()) << 32) | (ulong)random.Next();
                var offset   = random.Next(0, 256);

                EndianBitConverter.UInt64CopyBytesBe(expected, buffer, offset);

                var actual = EndianBitConverter.ToUInt64Be(buffer, offset);

                Assert.Equal(expected, actual);
            }
        }
        private static SocketAsyncEventArgs CreateArgs(byte[] data)
        {
            int len = data.Length;

            if (len <= 0 || len > ushort.MaxValue)
            {
                throw new ArgumentException($"Data length must be greater than 0 bytes and must not exceed {ushort.MaxValue} bytes.");
            }
            byte[] message  = new byte[len + 2];
            byte[] lenBytes = EndianBitConverter.Int16ToBytes((short)len, Endianness.LittleEndian);
            Buffer.BlockCopy(lenBytes, 0, message, 0, 2);
            Buffer.BlockCopy(data, 0, message, 2, len);
            var e = new SocketAsyncEventArgs();

            e.SetBuffer(message, 0, message.Length);
            return(e);
        }
示例#9
0
 public ByteBuffer(Endianness _endianess, System.Text.Encoding _encoding, int capacity, int position, MemoryStream _stream)
 {
     stream = new MemoryStream();
     if (_endianess == Endianness.BigEndian)
     {
         bitConverter = new BigEndianBitConverter();
     }
     else
     {
         bitConverter = new LittleEndianBitConverter();
     }
     writer          = new EndianBinaryWriter(bitConverter, stream, _encoding);
     reader          = new EndianBinaryReader(bitConverter, stream, _encoding);
     stream.Capacity = capacity;
     stream.Position = position;
     stream          = _stream;
 }
示例#10
0
        /// <summary>
        /// Creates the field from a stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns>The produced dBase field.</returns>
        /// <exception cref="System.ArgumentNullException">The stream is null.</exception>
        public static DBaseField FromStream(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream", "The stream is null.");
            }

            DBaseField result = new DBaseField();

            Byte[] buffer = new Byte[14];
            buffer[0] = (Byte)stream.ReadByte();

            if (buffer[0] == FieldTerminator) // we reached the end of the field descriptor
            {
                return(null);
            }

            stream.Read(buffer, 1, 10);

            for (Int32 i = 0; i < 11; i++)
            {
                if (buffer[i] == (Byte)0)
                {
                    result._nameLength = i;
                    break;
                }
            }

            if (result._nameLength == 0)
            {
                result._nameLength = 11;
            }

            result._name = Encoding.ASCII.GetString(buffer, 0, result._nameLength);
            result._type = Convert.ToChar(stream.ReadByte());

            stream.Read(buffer, 0, 4);
            result._dataAddress  = EndianBitConverter.ToInt32(buffer, 0, ByteOrder.LittleEndian);
            result._length       = stream.ReadByte();
            result._decimalCount = stream.ReadByte();

            stream.Read(buffer, 0, 14);

            return(result);
        }
示例#11
0
        public override Polygon Deserialize(ushort protocolVersion, byte[] buffer, int offset, int length, IColumnInfo typeInfo)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (length < 9)
            {
                throw new ArgumentException("A Polygon buffer should contain at least 9 bytes");
            }
            var isLe = IsLittleEndian(buffer, offset);

            offset++;
            var type = (GeometryType)EndianBitConverter.ToInt32(isLe, buffer, offset);

            if (type != GeometryType.Polygon)
            {
                throw new ArgumentException("Binary representation was not a Polygon");
            }
            offset += 4;
            var ringsLength = EndianBitConverter.ToInt32(isLe, buffer, offset);

            offset += 4;
            var ringsArray = new IList <Point> [ringsLength];

            for (var ringIndex = 0; ringIndex < ringsLength; ringIndex++)
            {
                var pointsLength = EndianBitConverter.ToInt32(isLe, buffer, offset);
                offset += 4;
                if (buffer.Length < offset + pointsLength * 16)
                {
                    throw new ArgumentException("Length of the buffer does not match");
                }
                var ring = new Point[pointsLength];
                for (var i = 0; i < pointsLength; i++)
                {
                    ring[i] = new Point(
                        EndianBitConverter.ToDouble(isLe, buffer, offset),
                        EndianBitConverter.ToDouble(isLe, buffer, offset + 8));
                    offset += 16;
                }
                ringsArray[ringIndex] = ring;
            }
            return(new Polygon(ringsArray));
        }
示例#12
0
        public static bool NeedsConversion(this Stream input)
        {
            var platform = input.GetAudioPlatform();
            EndianBitConverter bitConverter = platform.GetBitConverter();

            using (var MS = new MemoryStream())
                using (var reader = new EndianBinaryReader(bitConverter, MS)) {
                    input.Position = 0; input.CopyTo(MS);
                    MS.Position    = 0; input.Position = 0;
                    reader.Seek(16, SeekOrigin.Begin);
                    if (reader.ReadUInt32() == 24)
                    {
                        return(true);
                    }
                }

            return(false);
        }
示例#13
0
 /// <summary>
 /// Writes the specified floating point value to the array.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="radiometricResolution">The radiometric resolution of the value.</param>
 /// <param name="bytes">The byte array.</param>
 /// <param name="byteIndex">The zero-based byte index in the array.</param>
 /// <param name="bitIndex">The zero-based bit index in the array.</param>
 /// <exception cref="System.NotSupportedException">Radiometric resolution is not supported.</exception>
 private void WriteFloatValue(Double value, Int32 radiometricResolution, Byte[] bytes, ref Int32 byteIndex, ref Int32 bitIndex)
 {
     if (radiometricResolution == 32)
     {
         EndianBitConverter.CopyBytes((Single)value, bytes, byteIndex);
         byteIndex += 4;
     }
     else if (radiometricResolution == 64)
     {
         EndianBitConverter.CopyBytes(value, bytes, byteIndex);
         byteIndex += 8;
     }
     else
     {
         // TODO: support other resolutions
         throw new NotSupportedException("Radiometric resolution is not supported.");
     }
 }
示例#14
0
        public void ToBytes(byte[] buffer, int offset, EndianBitConverter bitConverter)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("byte buffer cannot be null");
            }
            if (buffer.Length < offset + 400)
            {
                throw new ArgumentException("buffer length is too small to write bytes from header to it");
            }

            bitConverter.CopyBytes(JobId, buffer, offset);
            bitConverter.CopyBytes(LineNum, buffer, offset + 4);
            bitConverter.CopyBytes(Reelnum, buffer, offset + 8);
            bitConverter.CopyBytes(DataTracesPerRecord, buffer, offset + 12);
            bitConverter.CopyBytes(AuxTracesPerRecord, buffer, offset + 14);
            bitConverter.CopyBytes(SampleIntervalOfFileMicrosec, buffer, offset + 16);
            bitConverter.CopyBytes(SampleIntervalOrigRecordingMicrosec, buffer, offset + 18);
            bitConverter.CopyBytes(SamplesPerTraceOfFile, buffer, offset + 20);
            bitConverter.CopyBytes(SamplesPerTraceOrigRecording, buffer, offset + 22);
            bitConverter.CopyBytes(DataSampleFormatCode, buffer, offset + 24);
            bitConverter.CopyBytes(CdpFold, buffer, offset + 26);
            bitConverter.CopyBytes(TraceSortingCode, buffer, offset + 28);
            bitConverter.CopyBytes(VerticalSumCode, buffer, offset + 30);
            bitConverter.CopyBytes(SweepFrequencyStart, buffer, offset + 32);
            bitConverter.CopyBytes(SweepFrequencyEnd, buffer, offset + 34);
            bitConverter.CopyBytes(SweepLengthMs, buffer, offset + 36);
            bitConverter.CopyBytes(SweepType, buffer, offset + 38);
            bitConverter.CopyBytes(TraceNumSweepChannel, buffer, offset + 40);
            bitConverter.CopyBytes(SweepTraceTaperLengthStartMs, buffer, offset + 42);
            bitConverter.CopyBytes(SweepTraceTaperLengthEndMs, buffer, offset + 44);
            bitConverter.CopyBytes(SweepTaperType, buffer, offset + 46);
            bitConverter.CopyBytes(CorrelatedDataTraces, buffer, offset + 48);
            bitConverter.CopyBytes(BinaryGainRecovered, buffer, offset + 50);
            bitConverter.CopyBytes(AplitudeRecovery, buffer, offset + 52);
            bitConverter.CopyBytes(UnitSystem, buffer, offset + 54);
            bitConverter.CopyBytes(ImpulseSignal, buffer, offset + 56);
            bitConverter.CopyBytes(VibratoryPolarityCode, buffer, offset + 58);

            bitConverter.CopyBytes(SegyFormatRevisionNum, buffer, offset + 300);
            bitConverter.CopyBytes(FixedLengthTraceFlag, buffer, offset + 302);
            bitConverter.CopyBytes(ExtendedTextHeadersCount, buffer, offset + 304);
        }
示例#15
0
        private Converter <object, byte[]> GetWriteMethod(PropertyInfo prop, EndianBitConverter bitConverter)
        {
            if (prop.CanWrite == false)
            {
                return(null);
            }

            var hbca = prop.GetCustomAttribute <HBaseConverterAttribute>();

            if (hbca != null)
            {
                var writer = Activator.CreateInstance(hbca.BinaryConverter);
                var write  = hbca.BinaryConverter.GetMethod(nameof(IByteArrayConverter.Write));
                if (write == null)
                {
                    return(null);
                }
                return(v => write.Invoke(writer, new[] { v, hbca.ConverterParameters }) as byte[]);
            }

            if (prop.PropertyType == typeof(string))
            {
                return(v => v.ToString().ToUtf8Bytes());
            }

            var propertyType = prop.PropertyType.Name == "Nullable`1" ? prop.PropertyType.GenericTypeArguments.FirstOrDefault() : prop.PropertyType;

            if (propertyType == null)
            {
                return(null);
            }

            var method = bitConverter.GetType().GetMethods().FirstOrDefault(t =>
                                                                            t.Name == nameof(EndianBitConverter.GetBytes) &&
                                                                            t.GetParameters().FirstOrDefault()?.ParameterType == propertyType);

            if (method == null)
            {
                return(null);
            }

            return(v => method.Invoke(bitConverter, new[] { v }) as byte[]);
        }
示例#16
0
        public void SendMessage(byte[] buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (Encryptor != null)
            {
                buffer = Encryptor.Encrypt(buffer);
            }

            byte[] dataSizeBytes = EndianBitConverter.GetBytes(buffer.Length);
            byte[] realBuffer    = new byte[buffer.Length + dataSizeBytes.Length];
            Array.Copy(dataSizeBytes, 0, realBuffer, 0, dataSizeBytes.Length);
            Array.Copy(buffer, 0, realBuffer, dataSizeBytes.Length, buffer.Length);

            Send(realBuffer);
        }
示例#17
0
        public byte[] ReceiveMessage()
        {
            try
            {
                lock (foo)
                {
                    // get the message size
                    byte[] messageSizeBytes = new byte[4];
                    int    dataLength;

                    int count = Receive(messageSizeBytes, 0, 4);

                    if (count != 4)
                    {
                        throw new Exception(string.Format("Received wrong amount in message size! Got: {0}, Expected: {1}", count, 4));
                    }

                    dataLength = EndianBitConverter.ToInt32(messageSizeBytes, 0);

                    // get the message
                    byte[] messageBytes = new byte[dataLength];

                    count = Receive(messageBytes, 0, dataLength);

                    if (count != dataLength)
                    {
                        throw new Exception(string.Format("Received wrong amount! Got: {0}, Expected: {1}", count, dataLength));
                    }

                    if (Encryptor != null)
                    {
                        messageBytes = Encryptor.Decrypt(messageBytes);
                    }

                    return(messageBytes);
                }
            }
            catch (Exception ex)
            {
                Disconnect(ex);
                return(null);
            }
        }
示例#18
0
        private Converter <ByteString, object> GetReadMethod(PropertyInfo prop, EndianBitConverter bitConverter)
        {
            if (prop.CanRead == false)
            {
                return(null);
            }

            var hca = prop.GetCustomAttribute <HBaseConverterAttribute>();

            if (hca?.BinaryConverter != null)
            {
                var read = hca.BinaryConverter.GetMethod(nameof(IByteArrayConverter.Read));
                if (read == null)
                {
                    return(null);
                }
                var reader = Activator.CreateInstance(hca.BinaryConverter);
                return(b => read.Invoke(reader, new object[] { b.ToArray(), prop.PropertyType, hca.ConverterParameters }));
            }

            if (prop.PropertyType == typeof(string))
            {
                return(b => b.ToStringUtf8());
            }

            var propertyType = prop.PropertyType.Name == "Nullable`1" ? prop.PropertyType.GenericTypeArguments.FirstOrDefault() : prop.PropertyType;

            if (propertyType == null)
            {
                return(null);
            }

            var method = bitConverter.GetType().GetMethods().FirstOrDefault(t =>
                                                                            t.Name.StartsWith("To") &&
                                                                            t.ReturnParameter.ParameterType == propertyType);

            if (method == null)
            {
                return(null);
            }

            return(b => method.Invoke(bitConverter, new object[] { b.ToByteArray(), 0 }));
        }
示例#19
0
文件: DLSID.cs 项目: Kermalis/DLS2
 public DLSID(byte[] data)
 {
     if (data is null)
     {
         throw new ArgumentNullException(nameof(data));
     }
     if (data.Length != 16)
     {
         throw new ArgumentOutOfRangeException(nameof(data.Length));
     }
     Data1 = (uint)EndianBitConverter.BytesToInt32(data, 0, Endianness.LittleEndian);
     Data2 = (ushort)EndianBitConverter.BytesToInt16(data, 4, Endianness.LittleEndian);
     Data3 = (ushort)EndianBitConverter.BytesToInt16(data, 6, Endianness.LittleEndian);
     Data4 = new byte[8];
     for (int i = 0; i < 8; i++)
     {
         Data4[i] = data[8 + i];
     }
 }
示例#20
0
        /// <summary>
        /// Converts the multi point to Well-known Binary (WKB) representation.
        /// </summary>
        /// <param name="geometry">The geometry.</param>
        /// <param name="byteOrder">The byte-order of the conversion.</param>
        /// <param name="dimension">The dimension of the geometry.</param>
        /// <returns>The WKB representation of the <paramref name="geometry" />.</returns>
        private static Byte[] ToWellKnownBinary(IMultiPoint geometry, ByteOrder byteOrder, Int32 dimension)
        {
            Byte[] geometryBytes = new Byte[9 + ((dimension == 3) ? 24 : 16) * geometry.Count];

            if (byteOrder == ByteOrder.LittleEndian)
            {
                geometryBytes[0] = 1;
            }

            if (dimension == 3)
            {
                EndianBitConverter.CopyBytes((Int32)WellKnownBinaryTypes.MultiPointZ, geometryBytes, 1, byteOrder);
            }
            else
            {
                EndianBitConverter.CopyBytes((Int32)WellKnownBinaryTypes.MultiPoint, geometryBytes, 1, byteOrder);
            }

            // number of points
            Int32 byteIndex = 5;

            EndianBitConverter.CopyBytes(geometry.Count, geometryBytes, byteIndex, byteOrder);
            byteIndex += 4;

            for (Int32 geometryIndex = 0; geometryIndex < geometry.Count; geometryIndex++)
            {
                EndianBitConverter.CopyBytes(geometry[geometryIndex].X, geometryBytes, byteIndex, byteOrder);
                EndianBitConverter.CopyBytes(geometry[geometryIndex].Y, geometryBytes, byteIndex + 8, byteOrder);

                if (dimension == 3)
                {
                    EndianBitConverter.CopyBytes(geometry[geometryIndex].Z, geometryBytes, byteIndex + 16, byteOrder);
                    byteIndex += 24;
                }
                else
                {
                    byteIndex += 16;
                }
            }

            return(geometryBytes);
        }
示例#21
0
        /// <summary>
        /// Converts the multi polygon to Well-known Binary (WKB) representation.
        /// </summary>
        /// <param name="geometry">The geometry.</param>
        /// <param name="byteOrder">The byte-order of the conversion.</param>
        /// <param name="dimension">The dimension of the geometry.</param>
        /// <returns>The WKB representation of the <paramref name="geometry" />.</returns>
        private static Byte[] ToWellKnownBinary(IMultiPolygon geometry, ByteOrder byteOrder, Int32 dimension)
        {
            Byte[] geometryBytes = new Byte[9 + 4 * geometry.Count +
                                            4 * geometry.Sum(polygon => polygon.HoleCount + 1) +
                                            ((dimension == 3) ? 24 : 16) * geometry.Sum(polygon => polygon.Shell.Count + polygon.Holes.Sum(hole => hole.Count))];

            if (byteOrder == ByteOrder.LittleEndian)
            {
                geometryBytes[0] = 1;
            }

            if (dimension == 3)
            {
                EndianBitConverter.CopyBytes((Int32)WellKnownBinaryTypes.MultiPolygonZ, geometryBytes, 1, byteOrder);
            }
            else
            {
                EndianBitConverter.CopyBytes((Int32)WellKnownBinaryTypes.MultiPolygon, geometryBytes, 1, byteOrder);
            }

            // number of polygons
            EndianBitConverter.CopyBytes(geometry.Count, geometryBytes, 5, byteOrder);
            Int32 byteIndex = 9;

            for (Int32 geometryIndex = 0; geometryIndex < geometry.Count; geometryIndex++)
            {
                // number of rings
                EndianBitConverter.CopyBytes(geometry[geometryIndex].HoleCount + 1, geometryBytes, byteIndex, byteOrder);
                byteIndex += 4;

                // shell
                ConvertCoordinates(geometryBytes, ref byteIndex, byteOrder, geometry[geometryIndex].Shell, dimension);

                // holes
                for (Int32 j = 0; j < geometry[geometryIndex].Holes.Count; j++)
                {
                    ConvertCoordinates(geometryBytes, ref byteIndex, byteOrder, geometry[geometryIndex].Holes[j], dimension);
                }
            }

            return(geometryBytes);
        }
示例#22
0
        /// <summary>
        ///     Constructs a new binary e.Reader with the given bit converter, reading
        ///     to the given stream, using the given encoding.
        /// </summary>
        /// <param name="bitConverter">Converter to use when reading data</param>
        /// <param name="stream">Stream to read data from</param>
        /// <param name="encoding">Encoding to use when reading character data</param>
        public EndianBinaryReader(EndianBitConverter bitConverter, Stream stream, Encoding encoding)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (!stream.CanRead)
            {
                throw new ArgumentException("Stream isn't writable", "stream");
            }
            BaseStream      = stream;
            BitConverter    = bitConverter ?? throw new ArgumentNullException("bitConverter");
            Encoding        = encoding ?? throw new ArgumentNullException("encoding");
            minBytesPerChar = 1;

            if (encoding is UnicodeEncoding)
            {
                minBytesPerChar = 2;
            }
        }
        public override byte[] Serialize(ushort protocolVersion, LineString value)
        {
            var buffer         = new byte[9 + value.Points.Count * 16];
            var isLittleEndian = UseLittleEndianSerialization();

            buffer[0] = isLittleEndian ? (byte)1 : (byte)0;
            var offset = 1;

            EndianBitConverter.SetBytes(isLittleEndian, buffer, offset, (int)GeometryType.LineString);
            offset += 4;
            EndianBitConverter.SetBytes(isLittleEndian, buffer, offset, value.Points.Count);
            offset += 4;
            foreach (var point in value.Points)
            {
                EndianBitConverter.SetBytes(isLittleEndian, buffer, offset, point.X);
                EndianBitConverter.SetBytes(isLittleEndian, buffer, offset + 8, point.Y);
                offset += 16;
            }
            return(buffer);
        }
示例#24
0
        private static int ReadNumber(byte[] buffer, EndianBitConverter converter)
        {
            switch (buffer.Length)
            {
            case 1:
                return(buffer[0]);

            case 2:
                return(converter.ToUInt16(buffer, 0));

            case 4:
                return((int)converter.ToUInt32(buffer, 0));

            case 8:
                return((int)converter.ToUInt64(buffer, 0));

            default:
                throw new PListFormatException($"Unexpected offset int size: {buffer.Length}.");
            }
        }
示例#25
0
        public static void Main(string[] args)
        {
            var xmlfile = args[0];
            var sngfile = args[1];

            using (FileStream fs = new FileStream(sngfile, FileMode.Create)) {
                // parse from XML
                Sng2014File sng = Sng2014File.ConvertSong(xmlfile);

                // write raw SNG data for diffing and inspection
                var raw = new FileStream(sngfile + ".raw", FileMode.Create);
                EndianBitConverter conv = EndianBitConverter.Little;
                EndianBinaryWriter w    = new EndianBinaryWriter(conv, raw);
                sng.Write(w);

                // write fully packed SNG
                Platform platform = new Platform(GamePlatform.Pc, GameVersion.RS2014);
                sng.writeSng(fs, platform);
            }
        }
示例#26
0
 /// <summary>
 /// Constructs a new binary reader with the given bit converter, reading
 /// to the given stream, using the given encoding.
 /// </summary>
 /// <param name="bitConverter">Converter to use when reading data</param>
 /// <param name="stream">Stream to read data from</param>
 /// <param name="encoding">Encoding to use when reading character data</param>
 public EndianBinaryReader([NotNull] EndianBitConverter bitConverter, [NotNull] Stream stream, [NotNull] Encoding encoding)
 {
     if (stream == null)
     {
         throw new ArgumentNullException(nameof(stream));
     }
     if (!stream.CanRead)
     {
         throw new ArgumentException("Stream isn't writable", nameof(stream));
     }
     _baseStream      = stream;
     BitConverter     = bitConverter ?? throw new ArgumentNullException(nameof(bitConverter));
     Encoding         = encoding ?? throw new ArgumentNullException(nameof(encoding));
     _decoder         = encoding.GetDecoder();
     _minBytesPerChar = 1;
     if (encoding is UnicodeEncoding)
     {
         _minBytesPerChar = 2;
     }
 }
示例#27
0
        internal Byte[] RRToByte()
        {
            Byte[] RRBytes = new Byte[24];

            UInt32 RawTimeStamp = 0;

            if (!(this.TimeStamp is String))
            {
                RawTimeStamp = (UInt32)((DateTime)this.TimeStamp - (new DateTime(1601, 1, 1))).TotalHours;
            }

            Array.Copy(EndianBitConverter.ToByte((UInt16)this.RecordType, true), 0, RRBytes, 2, 2);
            RRBytes[4] = 5;
            RRBytes[5] = (Byte)this.Rank;
            Array.Copy(EndianBitConverter.ToByte((UInt32)this.UpdatedAtSerial, true), 0, RRBytes, 8, 4);
            Array.Copy(EndianBitConverter.ToByte((UInt32)this.TTL, false), 0, RRBytes, 12, 4);
            Array.Copy(EndianBitConverter.ToByte(RawTimeStamp, true), 0, RRBytes, 20, 4);

            return(RRBytes);
        }
示例#28
0
        private void OnConnected(ITransport transport)
        {
            try {
                LoggingService.LogInfo("Transport {0} connected.", transport);

                if (transport.Encryptor != null)
                {
                    var dh = new DiffieHellmanManaged();

                    var keyxBytes = dh.CreateKeyExchange();
                    transport.Send(dh.CreateKeyExchange(), 0, keyxBytes.Length);

                    keyxBytes = new byte [transport.Encryptor.KeyExchangeLength];
                    transport.Receive(keyxBytes, 0, transport.Encryptor.KeyExchangeLength);

                    keyxBytes = dh.DecryptKeyExchange(keyxBytes);

                    var keyBytes = new byte[transport.Encryptor.KeySize];
                    var ivBytes  = new byte[transport.Encryptor.IvSize];
                    Array.Copy(keyxBytes, 0, keyBytes, 0, keyBytes.Length);
                    Array.Copy(keyxBytes, keyBytes.Length, ivBytes, 0, ivBytes.Length);

                    transport.Encryptor.SetKey(keyBytes, ivBytes);
                }

                var connectionType = EndianBitConverter.GetBytes(transport.ConnectionType);
                transport.Send(connectionType, 0, connectionType.Length);

                var networkId = Common.Utils.SHA512(transport.Network.NetworkName);
                transport.Send(networkId, 0, networkId.Length);

                // Ready, Steady, GO!

                var callback = connectCallbacks [transport];
                connectCallbacks.Remove(transport);
                callback(transport);
            } catch (Exception ex) {
                transport.Disconnect(ex);
                RaiseTransportError(transport, ex);
            }
        }
        public static async Task<List<AddressSection>> readSections(string inputFile, CancellationToken cancelToken, IProgress<ProgressInfo> progress)
        {
            string arguments = "DUMP -l \"" + inputFile + "\"";
            var result = await callWit(arguments, cancelToken, progress).ConfigureAwait(continueOnCapturedContext);

            List<AddressSection> sections = new List<AddressSection>();

            using (StringReader reader = new StringReader(result))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Contains("Delta between file offset and virtual address:"))
                    {
                        // remove next three lines to get to the section table
                        reader.ReadLine();
                        reader.ReadLine();
                        reader.ReadLine();
                        break;
                    }
                }
                EndianBitConverter endianBitConverter = EndianBitConverter.Big;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] columns = line.Split(':');
                    if (columns.Length == 5)
                    {
                        string unused = columns[0];
                        string[] offsets = columns[1].Split(new string[] { ".." }, StringSplitOptions.None);
                        var offsetBeg = endianBitConverter.ToUInt32(HexUtil.hexStringToByteArray(offsets[0]), 0);
                        var offsetEnd = endianBitConverter.ToUInt32(HexUtil.hexStringToByteArray(offsets[1]), 0);
                        string size = columns[2];
                        var fileDelta = endianBitConverter.ToUInt32(HexUtil.hexStringToByteArray(columns[3]), 0);
                        var sectionName = columns[4].Trim();
                        sections.Add(new AddressSection(offsetBeg, offsetEnd, fileDelta, sectionName));
                    }
                }

            }
            return sections;
        }
        /// <summary>
        /// Computes the Well-known Binary (WKB) representation.
        /// </summary>
        /// <param name="geometry">The geometry.</param>
        /// <param name="byteOrder">The byte-order of the conversion.</param>
        /// <param name="geometryModel">The geometry model of the conversion.</param>
        /// <returns>The WKB representation of the <paramref name="geometry" />.</returns>
        private static Byte[] ComputeWellKnownBinary(IMultiPoint geometry, ByteOrder byteOrder, GeometryModel geometryModel)
        {
            Byte[] geometryBytes = new Byte[9 + ((geometryModel == GeometryModel.Spatial3D) ? 24 : 16) * geometry.Count];

            if (byteOrder == ByteOrder.LittleEndian)
            {
                geometryBytes[0] = 1;
            }

            if (geometryModel == GeometryModel.Spatial3D)
            {
                EndianBitConverter.CopyBytes((Int32)WellKnownBinaryTypes.MultiPointZ, geometryBytes, 1, byteOrder);
            }
            else
            {
                EndianBitConverter.CopyBytes((Int32)WellKnownBinaryTypes.MultiPoint, geometryBytes, 1, byteOrder);
            }

            Int32 byteIndex = 5;

            EndianBitConverter.CopyBytes(geometry.Count, geometryBytes, byteIndex, byteOrder); // the number of points
            byteIndex += 4;

            for (Int32 i = 0; i < geometry.Count; i++)
            {
                EndianBitConverter.CopyBytes(geometry[i].X, geometryBytes, byteIndex, byteOrder);
                EndianBitConverter.CopyBytes(geometry[i].Y, geometryBytes, byteIndex + 8, byteOrder);

                if (geometryModel == GeometryModel.Spatial3D)
                {
                    EndianBitConverter.CopyBytes(geometry[i].Z, geometryBytes, byteIndex + 16, byteOrder);
                    byteIndex += 24;
                }
                else
                {
                    byteIndex += 16;
                }
            }

            return(geometryBytes);
        }
示例#31
0
        public override Point Deserialize(ushort protocolVersion, byte[] buffer, int offset, int length, IColumnInfo typeInfo)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (length != 21)
            {
                throw new ArgumentException("2D Point buffer should contain 21 bytes");
            }
            var isLe = IsLittleEndian(buffer, offset);
            var type = (GeometryType)EndianBitConverter.ToInt32(isLe, buffer, offset + 1);

            if (type != GeometryType.Point2D)
            {
                throw new ArgumentException("Binary representation was not a point");
            }
            return(new Point(
                       EndianBitConverter.ToDouble(isLe, buffer, offset + 5),
                       EndianBitConverter.ToDouble(isLe, buffer, offset + 13)));
        }
        /// <summary>
        /// Computes the WKB representation of a coordinate list.
        /// </summary>
        /// <param name="byteArray">The byte-array.</param>
        /// <param name="byteIndex">The starting index.</param>
        /// <param name="byteOrder">The byte-order of the conversion.</param>
        /// <param name="coordinateList">The coordinate list.</param>
        /// <param name="geometryModel">The geometry model of the conversion.</param>
        private static void ComputeCoordinateList(Byte[] byteArray, ref Int32 byteIndex, ByteOrder byteOrder, IList <Coordinate> coordinateList, GeometryModel geometryModel)
        {
            EndianBitConverter.CopyBytes(coordinateList.Count, byteArray, byteIndex, byteOrder); // the number of coordinates
            byteIndex += 4;

            for (Int32 i = 0; i < coordinateList.Count; i++)
            {
                EndianBitConverter.CopyBytes(coordinateList[i].X, byteArray, byteIndex, byteOrder);
                EndianBitConverter.CopyBytes(coordinateList[i].Y, byteArray, byteIndex + 8, byteOrder);

                if (geometryModel == GeometryModel.Spatial3D)
                {
                    EndianBitConverter.CopyBytes(coordinateList[i].Z, byteArray, byteIndex + 16, byteOrder);
                    byteIndex += 24;
                }
                else
                {
                    byteIndex += 16;
                }
            }
        }
 /// <summary>
 /// Constructs a new binary writer with the given bit converter, writing
 /// to the given stream, using the given encoding.
 /// </summary>
 /// <param name="bitConverter">Converter to use when writing data</param>
 /// <param name="stream">Stream to write data to</param>
 /// <param name="encoding">Encoding to use when writing character data</param>
 public EndianBinaryWriter(EndianBitConverter bitConverter, Stream stream, Encoding encoding)
 {
     if (bitConverter == null)
         {
             throw new ArgumentNullException("bitConverter");
         }
         if (stream == null)
         {
             throw new ArgumentNullException("stream");
         }
         if (encoding == null)
         {
             throw new ArgumentNullException("encoding");
         }
         if (!stream.CanWrite)
         {
             throw new ArgumentException("Stream isn't writable", "stream");
         }
         this.stream = stream;
         this.bitConverter = bitConverter;
         this.encoding = encoding;
 }
 /// <summary>
 /// Constructs a new binary writer with the given bit converter, writing
 /// to the given stream, using UTF-8 encoding.
 /// </summary>
 /// <param name="bitConverter">Converter to use when writing data</param>
 /// <param name="stream">Stream to write data to</param>
 public EndianBinaryWriter(EndianBitConverter bitConverter,
     Stream stream)
     : this(bitConverter, stream, Encoding.UTF8)
 {
 }