Beispiel #1
0
        public void Question_5_1_BasicCases()
        {
            int n        = BinaryHelpers.IntFromBinary("11111111");
            int m        = BinaryHelpers.IntFromBinary("101");
            int i        = 2;
            int j        = 4;
            int expected = BinaryHelpers.IntFromBinary("11110111");

            Validate(expected, n, m, i, j);

            i        = 0;
            j        = 2;
            expected = BinaryHelpers.IntFromBinary("11111101");
            Validate(expected, n, m, i, j);

            n        = BinaryHelpers.IntFromBinary("10101010");
            m        = BinaryHelpers.IntFromBinary("1000");
            j        = 3;
            expected = BinaryHelpers.IntFromBinary("10101000");
            Validate(expected, n, m, i, j);

            i        = 4;
            j        = 7;
            expected = BinaryHelpers.IntFromBinary("10001010");
            Validate(expected, n, m, i, j);
        }
Beispiel #2
0
 private void SaveFriction(float[][] ret)
 {
     try
     {
         var fileName = GetFrictionFileName(this.SaveResultFileName);
         var dirName  = Path.GetDirectoryName(fileName);
         if (!Directory.Exists(dirName))
         {
             Directory.CreateDirectory(dirName);
         }
         BinaryHelpers.ExecuteWriter((writer) =>
         {
             for (int i = 0; i < ret.Length; i++)
             {
                 for (int j = 0; j < ret[i].Length; j++)
                 {
                     writer.Write(ret[i][j]);
                 }
             }
         }, fileName);
     }
     catch (IOException e)
     {
         throw new XTMFRuntimeException("Unable to save distribution cache file!\r\n" + e.Message);
     }
 }
Beispiel #3
0
        protected override DxfObject PostParse()
        {
            foreach (var a in _objectIdsA)
            {
                ObjectIds.Add(a);
            }

            foreach (var b in _objectIdsB)
            {
                ObjectIds.Add(b);
            }

            foreach (var c in _objectIdsC)
            {
                ObjectIds.Add(c);
            }

            foreach (var d in _objectIdsD)
            {
                ObjectIds.Add(d);
            }

            _objectIdsA.Clear();
            _objectIdsB.Clear();
            _objectIdsC.Clear();
            _objectIdsD.Clear();

            ObjectData = BinaryHelpers.CombineBytes(_binaryObjectBytes);
            _binaryObjectBytes.Clear();

            return(this);
        }
Beispiel #4
0
        public void Init()
        {
            while (true)
            {
                UnityExecutables = GetUnityExecutablePath().Select(p => new UnityBinary(p));
                bool quitRequested = false;
                var  choices       = UnityExecutables.Select(e => new ConsoleChoice {
                    ChoiceDescription = e.ExecutableVersionString, ChoiceAction = () => UnityExecutable = e
                }).ToList();
                ConsoleHelpers.MultipleChoice(choices, () => quitRequested = true);
                if (quitRequested)
                {
                    break;
                }


                //replace with FindRegion here
                UnityVersionContainer currentVersion = FindRegionBytesByVersion(UnityExecutable.ExecutableVersion);

                //RegionBytes = UnityExecutable.ExecutableVersion >= UnityBinaryVersion.UNITY_2018_3_0 ? RegionBytes_2018_3 : RegionBytes_Pre2018_3;
                //JumpInstructionOffset = UnityExecutable.ExecutableVersion >= UnityBinaryVersion.UNITY_2018_3_0 ? JumpInstructionOffsetVersionB : JumpInstructionOffsetVersionA;
                PatchableByteAddress = BinaryHelpers.FindJumpInstructionAddress(UnityExecutable.ExecutablePath, currentVersion.RegionByteArray, currentVersion.InstructionOffset);
                PatchableByteValue   = GetPatchableByteValue(currentVersion);
                if (PatchableByteValue == currentVersion.DarkSkinIndicator)
                {
                    ConsoleHelpers.YesNoChoice("Revert to light skin?", () => PatchExecutable(currentVersion.LightSkinIndicator));
                }
                else
                {
                    ConsoleHelpers.YesNoChoice("Apply dark skin patch?", () => PatchExecutable(currentVersion.DarkSkinIndicator));
                }
            }
        }
Beispiel #5
0
        private void ProcessCarList(Chunk chunk)
        {
            var newSize = chunk.Size - Reader.AlignToBoundary(0x10);

            if (newSize % 0xD0 != 0)
            {
                throw new InvalidDataException("Malformed car list chunk");
            }

            Progress?.Report("Processing car list");

            while (Stream.Position < chunk.EndOffset)
            {
                var cti = BinaryHelpers.ReadStruct <CarTypeInfo>(Reader);

                //Debug.WriteLine("{0} {1} ({2})", cti.ManufacturerName, cti.BaseModelName, cti.UsageType);

                var acr = new AaronCarRecord();
                acr.BaseModelName     = cti.BaseModelName;
                acr.CarTypeName       = cti.CarTypeName;
                acr.ManufacturerName  = cti.ManufacturerName;
                acr.DefaultBasePaint  = cti.DefaultBasePaint;
                acr.DefaultSkinNumber = cti.DefaultSkinNumber;
                acr.Skinnable         = cti.Skinnable;
                acr.UsageType         = cti.UsageType;

                _carService.AddCar(acr);
                HashResolver.Add(cti.CarTypeNameHash, cti.CarTypeName);
            }

            this.GenerateHashes();
        }
Beispiel #6
0
        private static void BlockDecompress(Stream stream, byte[] outData)
        {
            while (stream.Position < stream.Length)
            {
                var header = BinaryHelpers.ReadStruct <CIPHeader>(stream);

                if (header.Magic != 0x55441122)
                {
                    throw new InvalidDataException($"Invalid magic! Expected 0x55441122, got 0x{header.Magic:X8}");
                }

                var data         = new byte[header.CSize - 24];
                var decompressed = new byte[header.USize];

                if (stream.Read(data, 0, data.Length) != data.Length)
                {
                    throw new InvalidDataException($"Failed to read {data.Length} bytes from stream");
                }

                Compressor.Decompress(data, decompressed);

                Array.ConstrainedCopy(
                    decompressed,
                    0,
                    outData,
                    header.UPos,
                    decompressed.Length);
            }
        }
Beispiel #7
0
        private void ProcessCarInfoArrayChunk(Chunk chunk, BinaryReader reader)
        {
            int alignedSize = chunk.GetAlignedSize(0x10);

            if (alignedSize % 0xD0 != 0)
            {
                throw new ChunkCorruptedException("CarTypeInfoArray is malformed!");
            }

            reader.AlignToBoundary(0x10);

            for (int i = 0; i < alignedSize / 0xD0; i++)
            {
                CarTypeInfo carTypeInfo = BinaryHelpers.ReadStruct <CarTypeInfo>(reader);
                CarRecord   carRecord   = new CarRecord
                {
                    BaseModelName     = carTypeInfo.BaseModelName,
                    CarTypeName       = carTypeInfo.CarTypeName,
                    DefaultBasePaint  = carTypeInfo.DefaultBasePaint,
                    DefaultSkinNumber = carTypeInfo.DefaultSkinNumber,
                    GeometryFilename  = carTypeInfo.GeometryFilename,
                    ManufacturerName  = carTypeInfo.ManufacturerName,
                    MemoryType        = (CarMemoryType)carTypeInfo.CarMemTypeHash,
                    Skinnable         = carTypeInfo.Skinnable,
                    UsageType         = carTypeInfo.UsageType
                };

                Database.CarRecordManager.AddCarRecord(carRecord);
            }
        }
Beispiel #8
0
 private void SaveFriction(float[][] ret)
 {
     try
     {
         var fileName = GetFrictionFileName(SaveFrictionFileName, -1);
         var dirName  = Path.GetDirectoryName(fileName);
         if (dirName == null)
         {
             throw new XTMFRuntimeException(this, $"In {Name} we were unable to get the directory name from the file {fileName}!");
         }
         if (!Directory.Exists(dirName))
         {
             Directory.CreateDirectory(dirName);
         }
         BinaryHelpers.ExecuteWriter(writer =>
         {
             for (int i = 0; i < ret.Length; i++)
             {
                 for (int j = 0; j < ret[i].Length; j++)
                 {
                     writer.Write(ret[i][j]);
                 }
             }
         }, fileName);
     }
     catch (IOException e)
     {
         throw new XTMFRuntimeException(this, "Unable to save distribution cache file!\r\n" + e.Message);
     }
 }
 public Input(string prevTxHash, UInt32 outpointIndex, UInt32 index, UInt32 sequence = 0xFFFFFFFF)
 {
     PrevTransactionHashBytes = BinaryHelpers.HexToByteArray(prevTxHash).Reverse().ToArray();
     OutpointIndex            = outpointIndex;
     Index     = index;
     Sequence  = sequence;
     ScriptSig = new Script(new byte[] { });
 }
Beispiel #10
0
 public static Addr FromWire(Wire.Network.Addr wire)
 {
     return(new Addr
     {
         EndPoint = new IPEndPoint(
             new IPAddress(BinaryHelpers.PackUInt64(wire.Ip)),
             (ushort)wire.Port)
     });
 }
Beispiel #11
0
 /// <summary>
 ///     Generates an alignment (null-filled) chunk to align the stream to the given byte boundary.
 /// </summary>
 /// <param name="boundary">The desired alignment.</param>
 public void AlignmentChunk(uint boundary)
 {
     if (_stream.Position % boundary != 0)
     {
         BeginChunk(0);
         BinaryHelpers.AlignStream(_stream, boundary);
         EndChunk();
     }
 }
Beispiel #12
0
 private void ProcessAttributes(Chunk chunk)
 {
     trackedUnknownAttributes.Clear();
     Progress?.Report("Processing attributes table");
     while (Stream.Position < chunk.EndOffset)
     {
         var carPartAttribute = BinaryHelpers.ReadStruct <CarPartAttribute>(Reader);
         _attributes.Add(carPartAttribute);
     }
 }
Beispiel #13
0
        private void ProcessPresetCars(Chunk chunk)
        {
            Progress?.Report("Processing preset cars");
            while (Stream.Position < chunk.EndOffset)
            {
                var fePresetCar = BinaryHelpers.ReadStruct <FEPresetCar>(Reader);

                _presetCarService.AddPresetCar(PresetConverter.ConvertFeToAaronPresetCar(fePresetCar));
            }
        }
Beispiel #14
0
        protected override DxfEntity PostParse()
        {
            GraphicsData = BinaryHelpers.CombineBytes(_graphicsDataBytes);
            _graphicsDataBytes.Clear();

            EntityData = BinaryHelpers.CombineBytes(_entityDataBytes);
            _entityDataBytes.Clear();

            return(this);
        }
        public static void Load()
        {
            if (!File.Exists(GameConts.ScoreLocation))
            {
                return;
            }
            Scores = BinaryHelpers.ReadFromBinaryFile <Scores>(GameConts.ScoreLocation);

            Scores.Score = Scores.Score.OrderByDescending(x => x.TimeTookMs) /*.ThenByDescending(x => x.AcScore)*/.ToList();
        }
 public void ByteArrayToHex()
 {
     foreach (var tuple in testCases)
     {
         var bytes       = tuple.Item2;
         var expectedHex = tuple.Item1.ToLower();
         var actualHex   = BinaryHelpers.ByteArrayToHex(bytes);
         Assert.AreEqual(expectedHex, actualHex);
     }
 }
 public void HexToByteArray()
 {
     foreach (var tuple in testCases)
     {
         var hex           = tuple.Item1;
         var expectedBytes = tuple.Item2;
         var actualBytes   = BinaryHelpers.HexToByteArray(hex);
         Assert.AreEqual(expectedBytes, actualBytes);
     }
 }
Beispiel #18
0
        public void TestBufferRoundTrip()
        {
            var marshalled            = BinaryHelpers.MarshalStruct(BenchmarkStructure);
            var unmarshalledStructure = BinaryHelpers.BufferToStructure <SimpleStructure>(marshalled);

            Assert.AreEqual(BenchmarkStructure.StringValue, unmarshalledStructure.StringValue);
            Assert.AreEqual(BenchmarkStructure.IntValue, unmarshalledStructure.IntValue);
            Assert.AreEqual(BenchmarkStructure.FloatValue, unmarshalledStructure.FloatValue);
            CollectionAssert.AreEqual(BenchmarkStructure.ByteArray, unmarshalledStructure.ByteArray);
        }
        protected internal override IEnumerable <DxfCodePair> GetSpecificPairs(DxfAcadVersion version, bool outputHandles, HashSet <IDxfItem> writtenItems)
        {
            yield return(new DxfCodePair(90, RawData.Length));

            // write lines in 128-byte chunks (expands to 256 hex bytes)
            foreach (var chunk in BinaryHelpers.ChunkBytes(RawData))
            {
                yield return(new DxfCodePair(310, chunk));
            }
        }
        public async override Task <Transaction> GetTransactionAsync(Transaction.Info info)
        {
            var json = JToken.Parse(await SendRPCAsync("blockchain.transaction.get", info.Hash, info.Height));

            var rawTx = BinaryHelpers.HexToByteArray(json["result"].Value <string>());
            var tx    = new Transaction(info.Height);

            tx.ReadPayload(new BinaryReader(new MemoryStream(rawTx)));

            return(tx);
        }
Beispiel #21
0
        /// <summary>
        /// Reads a compressed-in-place file. This involves reading a header and then
        /// proceeding to a shared routine for decompression.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static byte[] ReadBlockFile(Stream stream)
        {
            var br         = new BinaryReader(stream);
            var fileHeader = BinaryHelpers.ReadStruct <CIPFileHeader>(br);

            if (fileHeader.Magic != 0x66113388)
            {
                throw new InvalidDataException("Invalid header");
            }

            return(ReadCompressedBlocks(stream, fileHeader.USize));
        }
Beispiel #22
0
        public Wire.Network.Addr ToWire()
        {
            byte[] ipPadded = new byte[8];
            byte[] ipBytes  = EndPoint.Address.GetAddressBytes();
            Array.Copy(ipBytes, ipPadded, ipBytes.Length);

            return(new Wire.Network.Addr
            {
                Ip = BinaryHelpers.UnpackUInt64(ipPadded),
                Port = (ushort)EndPoint.Port
            });
        }
Beispiel #23
0
        public static byte[] WithHeader(byte[] message)
        {
            int i = BinaryHelpers.VarIntSize(message.Length);

            byte[] nmsg = new byte[message.Length + i];
            //Support.WriteToArray(nmsg, message.Length, 0);
            BinaryHelpers.WriteVarInt(nmsg, 0, message.Length);
            Array.Copy(message, 0, nmsg, i, message.Length);
            Debug.WriteLine($"Compression:  {nmsg.Length}/{Compress(nmsg, Compression.int16).Length}/{Compress(nmsg, Compression.int32).Length}/{Compress(nmsg, Compression.int64).Length}");
            Debug.WriteLine($"Matches: {Support.ArraysEqual(nmsg, Decompress(Compress(nmsg)))}");
            return(nmsg);
        }
Beispiel #24
0
        public byte[] GetSharedSecret(byte[] pK)
        {
            BitReader reader = new BitReader(pK);

            byte[] x            = reader.ReadByteArray();
            Point  remotePublic = new Point(
                new BigInteger(x),
                new BigInteger(reader.ReadByteArray(pK.Length - BinaryHelpers.VarIntSize(x.Length) - x.Length))
                );

            return(curve.Multiply(remotePublic, priv).X.ToByteArray()); // Use the x-coordinate as the shared secret
        }
Beispiel #25
0
 public void LoadData()
 {
     BinaryHelpers.ExecuteReader(this, (reader) =>
     {
         var matrix = new EmmeMatrix(reader);
         if (matrix.Dimensions != 2)
         {
             throw new XTMFRuntimeException(this, "In '" + Name + "' the matrix loaded in from '" + MatrixFile + "' was not an OD binary matrix!");
         }
         Data   = SparseTwinIndex <float> .CreateSquareTwinIndex(matrix.Indexes[0], matrix.Indexes[1], matrix.FloatData);
         Loaded = true;
     }, MatrixFile);
 }
Beispiel #26
0
 private static void CopyMatrix(IZone[] zones, string origin, string destination)
 {
     try
     {
         BinaryHelpers.ExecuteReader((reader =>
         {
             var matrix = new EmmeMatrix(reader);
             SaveData.SaveMatrix(zones, matrix.FloatData, destination);
         }), origin);
     }
     catch (IOException)
     {
     }
 }
Beispiel #27
0
 /// <summary>
 /// Sets the value of the patch byte in the Unity executable.
 /// </summary>
 private void PatchExecutable(byte b)
 {
     try
     {
         FileHelpers.CreateFileBackup(UnityExecutable.ExecutablePath);
         BinaryHelpers.WriteByteToAddress(UnityExecutable.ExecutablePath, b, PatchableByteAddress);
         ConsoleHelpers.WriteLine("Patch applied successfully", ConsoleColor.Green);
         Init();
     }
     catch
     {
         ConsoleHelpers.ExitOnInput("Failed to write changes to file, make sure you have write permission", ConsoleColor.Red);
     }
 }
Beispiel #28
0
        public void TestStreamRoundTrip()
        {
            using var ms = new MemoryStream();
            BinaryHelpers.WriteStruct(ms, BenchmarkStructure);
            ms.Position = 0;

            Assert.AreEqual(ms.Length, Marshal.SizeOf <SimpleStructure>());

            var unmarshalledStructure = BinaryHelpers.ReadStruct <SimpleStructure>(ms);

            Assert.AreEqual(BenchmarkStructure.StringValue, unmarshalledStructure.StringValue);
            Assert.AreEqual(BenchmarkStructure.IntValue, unmarshalledStructure.IntValue);
            Assert.AreEqual(BenchmarkStructure.FloatValue, unmarshalledStructure.FloatValue);
            CollectionAssert.AreEqual(BenchmarkStructure.ByteArray, unmarshalledStructure.ByteArray);
        }
Beispiel #29
0
        /// <summary>
        /// The sample rate is read from the flac header here.
        /// This can be extracted from bits 145-164 of the stream.
        /// More information: https://xiph.org/flac/format.html#metadata_block_streaminfo.
        /// </summary>
        /// <param name="stream">The flac file stream.</param>
        /// <returns>The sample rate.</returns>
        public static Fin <uint> ReadSampleRate(Stream stream)
        {
            long position = stream.Seek(SampleRateOffset, SeekOrigin.Begin);

            Debug.Assert(position == 18, $"Expected stream.Seek position to return 18, instead returned {position}");

            Span <byte> buffer    = stackalloc byte[3];
            int         bytesRead = stream.Read(buffer);

            if (bytesRead != buffer.Length)
            {
                return(FileTooShort);
            }

            return(BinaryHelpers.Read20BitUnsignedBigEndianIgnoringLastNibble(buffer));
        }
Beispiel #30
0
        /// <summary>
        /// The number of channels is read from the flac header here.
        /// This can be extracted from bits 165-167 of the stream.
        /// More information: https://xiph.org/flac/format.html#metadata_block_streaminfo.
        /// </summary>
        /// <param name="stream">The flac file stream.</param>
        /// <returns>The number of channels.</returns>
        public static Fin <byte> ReadNumChannels(Stream stream)
        {
            long position = stream.Seek(ChannelOffset, SeekOrigin.Begin);

            Debug.Assert(position == 20, $"Expected stream.Seek position to return 20, instead returned {position}");

            Span <byte> buffer    = stackalloc byte[1];
            int         bytesRead = stream.Read(buffer);

            if (bytesRead != buffer.Length)
            {
                return(FileTooShort);
            }

            return((byte)(BinaryHelpers.Read3BitUnsignedBigEndianIgnoringFirstFourAndLastBit(buffer) + 1));
        }