public static MidiData parse(FileStream input_file_stream) { var input_binary_reader = new BinaryReader(input_file_stream); HeaderChunk header_chunk; ushort number_of_tracks; { var header_chunk_ID = stringEncoder.GetString(input_binary_reader.ReadBytes(4)); var header_chunk_size = BitConverter.ToInt32(input_binary_reader.ReadBytes(4).Reverse().ToArray <byte>(), 0); var header_chunk_data = input_binary_reader.ReadBytes(header_chunk_size); var format_type = BitConverter.ToUInt16(header_chunk_data.Take(2).Reverse().ToArray <byte>(), 0); number_of_tracks = BitConverter.ToUInt16(header_chunk_data.Skip(2).Take(2).Reverse().ToArray <byte>(), 0); var time_division = BitConverter.ToUInt16(header_chunk_data.Skip(4).Take(2).Reverse().ToArray <byte>(), 0); header_chunk = new HeaderChunk(format_type, time_division); } var tracks = Enumerable.Range(0, number_of_tracks) .Select(track_number => { var track_chunk_ID = stringEncoder.GetString(input_binary_reader.ReadBytes(4)); var track_chunk_size = BitConverter.ToInt32(input_binary_reader.ReadBytes(4).Reverse().ToArray <byte>(), 0); var track_chunk_data = input_binary_reader.ReadBytes(track_chunk_size); return(Tuple.Create(track_chunk_size, track_chunk_data)); }).ToList() .Select(raw_track => new TrackChunk(parse_events(raw_track.Item2, raw_track.Item1))); return(new MidiData(header_chunk, tracks)); }
public void Update(Session session, JET_DBID dbid, Action <string> output) { using (var table = new Table(session, dbid, "indexes_stats", OpenTableGrbit.None)) { byte[] defaultValue = BitConverter.GetBytes(1); JET_COLUMNID columnid; Api.JetAddColumn(session, table, "priority", new JET_COLUMNDEF { coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, defaultValue, defaultValue.Length, out columnid); defaultValue = BitConverter.GetBytes(0); Api.JetAddColumn(session, table, "created_timestamp", new JET_COLUMNDEF { cbMax = 8, //64 bits coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, defaultValue, defaultValue.Length, out columnid); Api.JetAddColumn(session, table, "last_indexing_time", new JET_COLUMNDEF { cbMax = 8, //64 bits coltyp = JET_coltyp.Binary, grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL }, defaultValue, defaultValue.Length, out columnid); } SchemaCreator.UpdateVersion(session, dbid, "4.6"); }
public void WriteFloat(double value) { this.PrepareValue(); // ReSharper disable once CompareOfFloatsByEqualityOperator if (!this.forceFloat64 && value == (float)value) { // TODO: Increase testing coverage this.containerStack.IncreaseCurrentContainerLength(5); this.dataBuffer.WriteByte(TidFloatByte | 4); this.dataBuffer.WriteUint32(BitConverterEx.SingleToInt32Bits((float)value)); } else { this.containerStack.IncreaseCurrentContainerLength(9); this.dataBuffer.WriteByte(TidFloatByte | 8); if (double.IsNaN(value)) { // Double.NaN is different between C# and Java // For consistency, map NaN to the long value for NaN in Java this.dataBuffer.WriteUint64(0x7ff8000000000000L); } else { this.dataBuffer.WriteUint64(BitConverter.DoubleToInt64Bits(value)); } } this.FinishValue(); }
public static ASN1 FromInt32(Int32 value) { byte[] integer = BitConverterLE.GetBytes(value); Array.Reverse(integer); int x = 0; while ((x < integer.Length) && (integer[x] == 0x00)) { x++; } ASN1 asn1 = new ASN1(0x02); switch (x) { case 0: asn1.Value = integer; break; case 4: asn1.Value = new byte[1]; break; default: byte[] smallerInt = new byte[4 - x]; Buffer.BlockCopy(integer, x, smallerInt, 0, smallerInt.Length); asn1.Value = smallerInt; break; } return(asn1); }
public void Randomize(double num) { int num1 = _seed; int num2 = !BitConverter.IsLittleEndian ? BitConverter.ToInt32(BitConverter.GetBytes(num), 0) : BitConverter.ToInt32(BitConverter.GetBytes(num), 4); int num3 = (num2 & (int)ushort.MaxValue ^ num2 >> 16) << 8; int num4 = num1 & -16776961 | num3; _seed = num4; }
public byte[] GetHeaderPage() { _byteIterator = 0; var headerPage = new byte[Static.PageSize]; Array.Copy(BC.GetBytes(RootIndex), 0, headerPage, _byteIterator, sizeof(long)); _byteIterator += sizeof(long); return(headerPage); }
/// <summary> /// /// </summary> /// <param name="exp"></param> /// <returns></returns> public static double PowerOf2(int exp) { if (exp > 1023 || exp < -1022) { throw new ArgumentException("Exponent out of bounds"); } long expBias = exp + ExponentBias; long bits = expBias << 52; return(BitConverter.Int64BitsToDouble(bits)); }
public void Randomize() { System.DateTime now = System.DateTime.Now; float timer = (float)checked ((60 * now.Hour + now.Minute) * 60 + now.Second) + (float)now.Millisecond / 1000f; int num1 = _seed; int num2 = BitConverter.ToInt32(BitConverter.GetBytes(timer), 0); int num3 = (num2 & (int)ushort.MaxValue ^ num2 >> 16) << 8; int num4 = num1 & -16776961 | num3; _seed = num4; }
private static void TransferHeaders(Socket socket, int txDataLen, out int rxDataLen) { socket.Blocking = true; socket.Send(BitConverter.GetBytes(txDataLen)); byte[] buf4 = new byte[4]; int len = socket.Receive(buf4); if (len != 4) { throw new ApplicationException("Incomplete header received, len=" + len); } rxDataLen = BitConverter.ToInt32(buf4, 0); }
public void WriteRpcLog(int gameCode, string ipAddress, Shared.RpcCalls rpcCall, byte[] data) { if (data.Length > 240) { throw new Exception("Too much data. Please write max. 255 bytes at a time."); } BeginWriteLine((byte)Shared.LogType.Rpc, GetTime()); EncodeStream.WriteByte((byte)rpcCall); EncodeStream.Write(BitConverter.GetBytes(gameCode), 0, 4); EncodeStream.Write((IPAddress.Parse(ipAddress).GetAddressBytes()), 0, 4); EncodeStream.Write(data, 0, data.Length); EndWriteLine(); }
private UInt32 RVAtoPosition(UInt32 r, int sections, byte[] headers) { for (int i = 0; i < sections; i++) { UInt32 p = BitConverterLE.ToUInt32(headers, i * 40 + 20); UInt32 s = BitConverterLE.ToUInt32(headers, i * 40 + 12); var l = (int)BitConverterLE.ToUInt32(headers, i * 40 + 8); if ((s <= r) && (r < s + l)) { return(p + r - s); } } return(0); }
public static RpcLog Deserialize(SelfDecoder.BinaryLog source) { var log = new RpcLog(); log.Type = (Shared.RpcCalls)source.LogData[0]; var buffer = new byte[4]; Buffer.BlockCopy(source.LogData, 1, buffer, 0, 4); log.GameCode = BitConverter.ToInt32(buffer, 0); Buffer.BlockCopy(source.LogData, 5, buffer, 0, 4); log.IpAddress = new IPAddress(buffer).ToString(); buffer = new byte[source.LogData.Length - 9]; Buffer.BlockCopy(source.LogData, 9, buffer, 0, buffer.Length); log.RpcData = buffer; return(log); }
public float VBNext(float num) { int num1 = _seed; if ((double)num != 0.0) { if ((double)num < 0.0) { long num2 = (long)BitConverter.ToInt32(BitConverter.GetBytes(num), 0) & (long)uint.MaxValue; num1 = checked ((int)(num2 + (num2 >> 24) & 16777215L)); } num1 = checked ((int)((long)num1 * 1140671485L + 12820163L & 16777215L)); } _seed = num1; return((float)num1 / 1.677722E+07f); }
/// <summary> /// Computes a hash code for a double value, using the algorithm from /// Joshua Bloch's book <i>Effective Java"</i> /// </summary> /// <param name="value">A hashcode for the double value</param> public static int GetHashCode(double value) { /* * From the java language specification, it says: * * The value of n>>>s is n right-shifted s bit positions with zero-extension. * If n is positive, then the result is the same as that of n>>s; if n is * negative, the result is equal to that of the expression (n>>s)+(2<<~s) if * the type of the left-hand operand is int */ var f = BitConverter.DoubleToInt64Bits(value); //if (f > 0) return((int)(f ^ (f >> 32))); //return (int) (f ^ ((f >> 32) + (2 << ~32))); }
public override async Task Decode(EbmlParser parser, bool forceDecode = false) { if (Decoded && !forceDecode) { return; } if (parser == null) { throw new ArgumentNullException(nameof(parser)); } if (parser.DataAccessor == null) { throw new InvalidOperationException( ExceptionsResourceManager.ResourceManager.GetString("InvalidDecodeState", CultureInfo.CurrentCulture)); } switch (DataSize.DataSize) { case 0: Value = 0; break; case 4: var floatBuffer = new byte[4]; parser.DataAccessor.Position = DataPosition; await parser.DataAccessor.ReadAsync(floatBuffer, 0, 4).ConfigureAwait(false); Utility.ConvertEndiannes(floatBuffer); Value = BitConverter.ToSingle(floatBuffer); break; case 8: var doubleBuffer = new byte[8]; parser.DataAccessor.Position = DataPosition; await parser.DataAccessor.ReadAsync(doubleBuffer, 0, 8).ConfigureAwait(false); Utility.ConvertEndiannes(doubleBuffer); Value = BitConverter.ToDouble(doubleBuffer); break; default: throw new DecodeException("Can not decode a decimal number that is not either 0, 4 or 8 bytes long"); } Decoded = true; }
/// <summary> /// Return HashCode. /// </summary> public override int GetHashCode() { long bits0 = BitConverter.DoubleToInt64Bits(_p0.X); bits0 ^= BitConverter.DoubleToInt64Bits(_p0.Y) * 31; int hash0 = (((int)bits0) ^ ((int)(bits0 >> 32))); long bits1 = BitConverter.DoubleToInt64Bits(_p1.X); bits1 ^= BitConverter.DoubleToInt64Bits(_p1.Y) * 31; int hash1 = (((int)bits1) ^ ((int)(bits1 >> 32))); // XOR is supposed to be a good way to combine hashcodes return(hash0 ^ hash1); //return base.GetHashCode(); }
public static BinaryLog Deserialize(MemoryStream stream, byte baseLength) { var type = stream.ReadByte(); var buffer = new byte[8]; stream.Read(buffer, 0, 8); var epoch = BitConverter.ToUInt64(buffer, 0); buffer = new byte[baseLength - 9]; stream.Read(buffer, 0, buffer.Length); return(new BinaryLog { BaseLength = baseLength, Type = (Shared.LogType)type, TimeStamp = GetTime(epoch), LogData = buffer }); }
public void WriteFloat(double value) { PrepareValue(); // ReSharper disable once CompareOfFloatsByEqualityOperator if (value == (float)value) { //TODO requires careful testing _containerStack.IncreaseCurrentContainerLength(5); _dataBuffer.WriteByte(TidFloatByte | 4); _dataBuffer.WriteUint32(BitConverterEx.SingleToInt32Bits((float)value)); } else { _containerStack.IncreaseCurrentContainerLength(9); _dataBuffer.WriteByte(TidFloatByte | 8); _dataBuffer.WriteUint64(BitConverterEx.DoubleToInt64Bits(value)); } FinishValue(); }
public BTreePage(byte[] pageData) { _byteIterator = 0; Records = new List <NodeRecord> { Capacity = (int)Static.MemMax }; Childrens = new List <long> { Capacity = (int)Static.ChilMax }; ParentIndex = BC.ToInt64(pageData, _byteIterator); _byteIterator += sizeof(long); SelfIndex = BC.ToInt64(pageData, _byteIterator); _byteIterator += sizeof(long); _presentRecords = BC.ToInt64(pageData, _byteIterator); _byteIterator += sizeof(long); IsLeaf = BC.ToBoolean(pageData, _byteIterator); _byteIterator += sizeof(bool); for (var i = 0; i < _presentRecords; i++) { var key = BC.ToInt64(pageData, _byteIterator); _byteIterator += sizeof(long); var pageIndex = BC.ToInt64(pageData, _byteIterator); _byteIterator += sizeof(long); Records.Add(new NodeRecord(key, pageIndex)); } if (!IsLeaf) { for (var i = 0; i < _presentRecords + 1; i++) { Childrens.Add(BC.ToInt64(pageData, _byteIterator)); _byteIterator += sizeof(long); } } }
public DataPage(byte[] page) { _byteIterator = 0; Records = new List <Record> { Capacity = Static.GetRecordsPerPage() }; UsedSpace = BC.ToInt32(page, _byteIterator); _byteIterator += sizeof(int); for (var i = 0; i < UsedSpace; i++) { var key = BC.ToUInt32(page, _byteIterator); _byteIterator += sizeof(uint); var radius = BC.ToDouble(page, _byteIterator); _byteIterator += sizeof(double); var angle = BC.ToInt16(page, _byteIterator); _byteIterator += sizeof(short); Records.Add(new Record(key, radius, angle)); } }
public byte[] GetDataPage() { _byteIterator = 0; UsedSpace = Records.Count; var page = new byte[Static.PageSize]; Array.Copy(BC.GetBytes(UsedSpace), 0, page, _byteIterator, sizeof(int)); _byteIterator += sizeof(int); for (var i = 0; i < UsedSpace; i++) { Array.Copy(BC.GetBytes(Records[i].Key), 0, page, _byteIterator, sizeof(uint)); _byteIterator += sizeof(uint); Array.Copy(BC.GetBytes(Records[i].Radius), 0, page, _byteIterator, sizeof(double)); _byteIterator += sizeof(double); Array.Copy(BC.GetBytes(Records[i].Angle), 0, page, _byteIterator, sizeof(short)); _byteIterator += sizeof(short); } return(page); }
public byte[] GetBTreePage() { _byteIterator = 0; var page = new byte[Static.PageSize]; _presentRecords = Records.Count; Array.Copy(BC.GetBytes(ParentIndex), 0, page, _byteIterator, sizeof(long)); _byteIterator += sizeof(long); Array.Copy(BC.GetBytes(SelfIndex), 0, page, _byteIterator, sizeof(long)); _byteIterator += sizeof(long); Array.Copy(BC.GetBytes(_presentRecords), 0, page, _byteIterator, sizeof(long)); _byteIterator += sizeof(long); Array.Copy(BC.GetBytes(IsLeaf), 0, page, _byteIterator, sizeof(bool)); _byteIterator += sizeof(bool); for (var i = 0; i < _presentRecords; i++) { var key = BC.GetBytes(Records[i].Key); var pageIndex = BC.GetBytes(Records[i].RecordIndex); Array.Copy(key, 0, page, _byteIterator, sizeof(long)); _byteIterator += sizeof(long); Array.Copy(pageIndex, 0, page, _byteIterator, sizeof(long)); _byteIterator += sizeof(long); } if (!IsLeaf) { for (var i = 0; i < _presentRecords + 1; i++) { Array.Copy(BC.GetBytes(Childrens[i]), 0, page, _byteIterator, sizeof(long)); _byteIterator += sizeof(long); } } return(page); }
/// <summary> /// /// </summary> /// <param name="x"></param> public DoubleBits(double x) { this.x = x; _xBits = BitConverter.DoubleToInt64Bits(x); }
private static int GetHashCode(double value) { var f = BitConverter.DoubleToInt64Bits(value); return((int)(f ^ (f >> 32))); }
private void BeginWriteLine(byte logType, UInt64 unixTimeMs) { EncodeStream.WriteByte(logType); EncodeStream.Write(BitConverter.GetBytes(unixTimeMs), 0, 8); }
private static MIDIEvent_Length_Tuple next_event(ByteEnumerable track_data, int start_index, byte last_midi_channel) { var i = start_index - 1; MidiEvent midi_event = null; { var delta_time = 0; { var length_temp = new ByteList(); do { i += 1; length_temp.Add(track_data.ElementAt(i)); } while (track_data.ElementAt(i) > 0x7F); delta_time = VariableLengthUtil.decode_to_int(length_temp); } i += 1; var event_type_value = track_data.ElementAt(i); // MIDI Channel Events if ((event_type_value & 0xF0) < 0xF0) { var midi_channel_event_type = (byte)(event_type_value & 0xF0); var midi_channel = (byte)(event_type_value & 0x0F); i += 1; var parameter_1 = track_data.ElementAt(i); var parameter_2 = (byte)0x00; // One or two parameter type switch (midi_channel_event_type) { // One parameter types case 0xC0: midi_event = new ProgramChangeEvent(delta_time, midi_channel, parameter_1); last_midi_channel = midi_channel; break; case 0xD0: midi_event = new ChannelAftertouchEvent(delta_time, midi_channel, parameter_1); last_midi_channel = midi_channel; break; // Two parameter types case 0x80: i += 1; parameter_2 = track_data.ElementAt(i); midi_event = new NoteOffEvent(delta_time, midi_channel, parameter_1, parameter_2); last_midi_channel = midi_channel; break; case 0x90: i += 1; parameter_2 = track_data.ElementAt(i); midi_event = new NoteOnEvent(delta_time, midi_channel, parameter_1, parameter_2); last_midi_channel = midi_channel; break; case 0xA0: i += 1; parameter_2 = track_data.ElementAt(i); midi_event = new NoteAftertouchEvent(delta_time, midi_channel, parameter_1, parameter_2); last_midi_channel = midi_channel; break; case 0xB0: i += 1; parameter_2 = track_data.ElementAt(i); midi_event = new ControllerEvent(delta_time, midi_channel, parameter_1, parameter_2); last_midi_channel = midi_channel; break; case 0xE0: i += 1; parameter_2 = track_data.ElementAt(i); midi_event = new PitchBendEvent(delta_time, midi_channel, parameter_1, parameter_2); last_midi_channel = midi_channel; break; // Might be a Control Change Messages LSB default: midi_event = new ControllerEvent(delta_time, last_midi_channel, event_type_value, parameter_1); break; } i += 1; } // Meta Events else if (event_type_value == 0xFF) { i += 1; var meta_event_type = track_data.ElementAt(i); i += 1; var meta_event_length = track_data.ElementAt(i); i += 1; var meta_event_data = Enumerable.Range(i, meta_event_length).Select(b => track_data.ElementAt(b)).ToArray(); switch (meta_event_type) { case 0x00: midi_event = new SequenceNumberEvent(BitConverter.ToUInt16(meta_event_data.Reverse().ToArray <byte>(), 0)); break; case 0x01: midi_event = new TextEvent(delta_time, stringEncoder.GetString(meta_event_data)); break; case 0x02: midi_event = new CopyrightNoticeEvent(stringEncoder.GetString(meta_event_data)); break; case 0x03: midi_event = new SequenceOrTrackNameEvent(stringEncoder.GetString(meta_event_data)); break; case 0x04: midi_event = new InstrumentNameEvent(delta_time, stringEncoder.GetString(meta_event_data)); break; case 0x05: midi_event = new LyricsEvent(delta_time, stringEncoder.GetString(meta_event_data)); break; case 0x06: midi_event = new MarkerEvent(delta_time, stringEncoder.GetString(meta_event_data)); break; case 0x07: midi_event = new CuePointEvent(delta_time, stringEncoder.GetString(meta_event_data)); break; case 0x20: midi_event = new MIDIChannelPrefixEvent(delta_time, meta_event_data[0]); break; case 0x2F: midi_event = new EndOfTrackEvent(delta_time); break; case 0x51: var tempo = (meta_event_data[2] & 0x0F) + ((meta_event_data[2] & 0xF0) * 16) + ((meta_event_data[1] & 0x0F) * 256) + ((meta_event_data[1] & 0xF0) * 4096) + ((meta_event_data[0] & 0x0F) * 65536) + ((meta_event_data[0] & 0xF0) * 1048576); midi_event = new SetTempoEvent(delta_time, tempo); break; case 0x54: midi_event = new SMPTEOffsetEvent(delta_time, meta_event_data[0], meta_event_data[1], meta_event_data[2], meta_event_data[3], meta_event_data[4]); break; case 0x58: midi_event = new TimeSignatureEvent(delta_time, meta_event_data[0], meta_event_data[1], meta_event_data[2], meta_event_data[3]); break; case 0x59: midi_event = new KeySignatureEvent(delta_time, meta_event_data[0], meta_event_data[1]); break; case 0x7F: midi_event = new SequencerSpecificEvent(delta_time, meta_event_data); break; } i += meta_event_length; } // System Exclusive Events else if (event_type_value == 0xF0 || event_type_value == 0xF7) { var event_length = 0; { var length_temp = new ByteList(); do { i += 1; length_temp.Add(track_data.ElementAt(i)); } while (track_data.ElementAt(i) > 0x7F); event_length = VariableLengthUtil.decode_to_int(length_temp); } i += 1; var event_data = Enumerable.Range(i, event_length).Select(b => track_data.ElementAt(b)); midi_event = new SysexEvent(delta_time, event_type_value, event_data); i += event_length; } } switch (midi_event != null) { case true: return(new MIDIEvent_Length_Tuple(new SomeMidiEvent(midi_event), i - start_index, last_midi_channel)); } return(new MIDIEvent_Length_Tuple(new NoMidiEvent(), i - start_index, last_midi_channel)); }
private void _ReadEmblemFullInfo() { //loop here in case it runs this too early and reads 0 max emblems because it's not initialized in the game yet int tries = 0, maxEmblems = 0, maxExtra = 0; do { //read the number of emblems loaded into the game byte[] maxEmblemsBuffer = new byte[4]; byte[] maxExtraBuffer = new byte[4]; ReadProcessMemory(gameProc.Handle, MAX_EMBLEMS_ADDRESS, maxEmblemsBuffer, 4, IntPtr.Zero); ReadProcessMemory(gameProc.Handle, MAX_EXTRA_EMBLEMS_ADDRESS, maxExtraBuffer, 4, IntPtr.Zero); maxEmblems = BC.ToInt32(maxEmblemsBuffer, 0); maxExtra = BC.ToInt32(maxExtraBuffer, 0); if (maxEmblems + maxExtra != 0) { break; } Thread.Sleep(2000); tries++; }while (tries < 5); Emblems = new Emblem[maxEmblems]; ExtraEmblems = new ExtraEmblem[maxExtra]; byte[] currentEmblem = new byte[128]; //size of 1 emblem object in memory int address = EMBLEMS_ADDRESS; for (int i = 0; i < Emblems.Length; i++) { ReadProcessMemory(gameProc.Handle, address, currentEmblem, currentEmblem.Length, IntPtr.Zero); //WriteProcessMemory(gameProc.Handle, address + 4, new byte[1] { 1 }, 1, IntPtr.Zero); //for the fun stuff Emblems[i] = new Emblem() { type = currentEmblem[0], tag = BC.ToInt16(currentEmblem, 2), level = BC.ToInt16(currentEmblem, 4), sprite = Convert.ToChar(currentEmblem[6]), color = BC.ToUInt16(currentEmblem, 8), var = BC.ToInt32(currentEmblem, 12), hint = Encoding.ASCII.GetString(currentEmblem, 16, 110), collected = currentEmblem[126] }; address += 128; } currentEmblem = new byte[68]; //size of 1 extra emblem object in memory address = EXTRA_EMBLEMS_ADDRESS; for (int i = 0; i < ExtraEmblems.Length; i++) { ReadProcessMemory(gameProc.Handle, address, currentEmblem, currentEmblem.Length, IntPtr.Zero); ExtraEmblems[i] = new ExtraEmblem() { name = Encoding.ASCII.GetString(currentEmblem, 0, 20), description = Encoding.ASCII.GetString(currentEmblem, 20, 40), conditionset = currentEmblem[60], showconditionset = currentEmblem[61], sprite = Convert.ToChar(currentEmblem[62]), color = BC.ToUInt16(currentEmblem, 64), collected = currentEmblem[66], }; address += 68; } if (!(previousEmblems.SequenceEqual(Emblems) && previousExtraEmblems.SequenceEqual(ExtraEmblems))) { EmblemsChangedEvent(this, EmblemsChangedEventArgs.FullInfo); } previousEmblems = (Emblem[])Emblems.Clone(); previousExtraEmblems = (ExtraEmblem[])ExtraEmblems.Clone(); }
/// <summary> /// Wrapper for <see cref="BitConverter.ToInt32">BitConverter.ToInt32</see> /// To automatically check for system endianness. /// </summary> /// <param name="value"></param> /// <param name="startIndex"></param> /// <returns></returns> public static int ToInt32(byte[] value, int startIndex = 0) { return(BitConverter.IsLittleEndian ? BitConverter.ToInt32(value.Reverse().ToArray(), 0) : BitConverter.ToInt32(value, 0)); }
internal StrongNameSignature StrongHash(Stream stream, StrongNameOptions options) { var info = new StrongNameSignature(); HashAlgorithm hash = HashAlgorithm.Create(TokenAlgorithm); var cs = new CryptoStream(Stream.Null, hash, CryptoStreamMode.Write); // MS-DOS Header - always 128 bytes // ref: Section 24.2.1, Partition II Metadata var mz = new byte[128]; stream.Read(mz, 0, 128); if (BitConverterLE.ToUInt16(mz, 0) != 0x5a4d) { return(null); } UInt32 peHeader = BitConverterLE.ToUInt32(mz, 60); cs.Write(mz, 0, 128); if (peHeader != 128) { var mzextra = new byte[peHeader - 128]; stream.Read(mzextra, 0, mzextra.Length); cs.Write(mzextra, 0, mzextra.Length); } // PE File Header - always 248 bytes // ref: Section 24.2.2, Partition II Metadata var pe = new byte[248]; stream.Read(pe, 0, 248); if (BitConverterLE.ToUInt32(pe, 0) != 0x4550) { return(null); } if (BitConverterLE.ToUInt16(pe, 4) != 0x14c) { return(null); } // MUST zeroize both CheckSum and Security Directory var v = new byte[8]; Buffer.BlockCopy(v, 0, pe, 88, 4); Buffer.BlockCopy(v, 0, pe, 152, 8); cs.Write(pe, 0, 248); UInt16 numSection = BitConverterLE.ToUInt16(pe, 6); int sectionLength = (numSection * 40); var sectionHeaders = new byte[sectionLength]; stream.Read(sectionHeaders, 0, sectionLength); cs.Write(sectionHeaders, 0, sectionLength); UInt32 cliHeaderRVA = BitConverterLE.ToUInt32(pe, 232); UInt32 cliHeaderPos = RVAtoPosition(cliHeaderRVA, numSection, sectionHeaders); var cliHeaderSiz = (int)BitConverterLE.ToUInt32(pe, 236); // CLI Header // ref: Section 24.3.3, Partition II Metadata var cli = new byte[cliHeaderSiz]; stream.Position = cliHeaderPos; stream.Read(cli, 0, cliHeaderSiz); UInt32 strongNameSignatureRVA = BitConverterLE.ToUInt32(cli, 32); info.SignaturePosition = RVAtoPosition(strongNameSignatureRVA, numSection, sectionHeaders); info.SignatureLength = BitConverterLE.ToUInt32(cli, 36); UInt32 metadataRVA = BitConverterLE.ToUInt32(cli, 8); info.MetadataPosition = RVAtoPosition(metadataRVA, numSection, sectionHeaders); info.MetadataLength = BitConverterLE.ToUInt32(cli, 12); if (options == StrongNameOptions.Metadata) { cs.Close(); hash.Initialize(); var metadata = new byte[info.MetadataLength]; stream.Position = info.MetadataPosition; stream.Read(metadata, 0, metadata.Length); info.Hash = hash.ComputeHash(metadata); return(info); } // now we hash every section EXCEPT the signature block for (int i = 0; i < numSection; i++) { UInt32 start = BitConverterLE.ToUInt32(sectionHeaders, i * 40 + 20); var length = (int)BitConverterLE.ToUInt32(sectionHeaders, i * 40 + 16); var section = new byte[length]; stream.Position = start; stream.Read(section, 0, length); if ((start <= info.SignaturePosition) && (info.SignaturePosition < start + length)) { // hash before the signature var before = (int)(info.SignaturePosition - start); if (before > 0) { cs.Write(section, 0, before); } // copy signature info.Signature = new byte[info.SignatureLength]; Buffer.BlockCopy(section, before, info.Signature, 0, (int)info.SignatureLength); Array.Reverse(info.Signature); // hash after the signature var s = (int)(before + info.SignatureLength); int after = (length - s); if (after > 0) { cs.Write(section, s, after); } } else { cs.Write(section, 0, length); } } cs.Close(); info.Hash = hash.Hash; return(info); }
public BTreeHeaderPage(byte[] headerPage) { RootIndex = BC.ToInt64(headerPage, _byteIterator); _byteIterator += sizeof(long); }