Here are the examples of the csharp api System.BitConverter.ToInt32(byte[], int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2288 Examples
19
View Source File : RansomNote.cs
License : GNU General Public License v3.0
Project Creator : 0x00000FF
License : GNU General Public License v3.0
Project Creator : 0x00000FF
private void Detect()
{
while (true)
{
if (!flag)
{
var Procs = Process.GetProcessesByName("th12");
if (Procs.Length > 0)
{
// Open TH12.exe with PROCESS_VM_READ (0x0010).
_handle = OpenProcess(0x10, false, Procs.FirstOrDefault().Id);
if (_handle != null)
processStatus = true;
}
}
else
{
if (IsScoreReached)
{
break;
}
int bytesRead = 0;
byte[] _buffer = new byte[4]; // Will read 4 bytes of memory
/*
* Read Level
*
* In TH12 ~ Undefined Fantastic Object, Level is stored in
* [base address] + 0xAEBD0, as 4bytes int value.
*
*/
var readLevel = ReadProcessMemory((int)_handle, 0x004AEBD0, _buffer, 2, ref bytesRead);
if (!readLevel)
{
flag = false;
continue;
}
/*
* Level Codes
* 0 - Easy; 1 - Normal; 2 - Hard; 3 - Lunatic; ? - Extra
*
*/
if (BitConverter.ToInt16(_buffer, 0) != 3)
{
ProcStatus.Invoke(new MethodInvoker(() => {
ProcStatus.Text = "NOT LUNATIC LEVEL!";
}));
continue;
}
else
{
ProcStatus.Invoke(new MethodInvoker(() => {
ProcStatus.Text = "Process Working";
}));
}
/*
* Read Score
*
* Once level is detected as LUNATIC,
* rensenWare reads score from process.
*
* Score is stored in
* [base address] + 0xB0C44, as 4bytes int value.
*
*/
var readScore = ReadProcessMemory((int)_handle, 0x004B0C44, _buffer, 4, ref bytesRead);
if (!readScore)
{
flag = false;
continue;
}
ScoreStatus.Invoke(new MethodInvoker(() =>
{
ScoreStatus.Text = (BitConverter.ToInt32(_buffer, 0) * 10).ToString();
}));
/*
* One interesting thing,
* internally, touhou project process prints score as 10 times of original value.
* I don't know why it is.
*/
if (BitConverter.ToInt32(_buffer, 0) > 20000000) // It is 20,000,000
IsScoreReached = true;
else
_buffer = null;
}
// Let CPU rest
Thread.Sleep(100);
}
// Create Random Key/IV File in Desktop of Current User.
File.WriteAllBytes(Program.KeyFilePath, Program.randomKey);
File.WriteAllBytes(Program.IVFilePath, Program.randomIV);
decryptProgress.Maximum = Program.encryptedFiles.Count;
foreach (var path in Program.encryptedFiles)
{
try
{
DecryptStatus.Invoke(new MethodInvoker(() =>
{
DecryptStatus.Text = Path.GetFileName(path);
}));
// Do Decrypt
decryptProgress.Value++;
}
catch
{
continue;
}
}
this.Invoke(new MethodInvoker(() => {
MessageBox.Show("Decryption Complete!\nIf there are encrypted files exists, use manual decrypter with key/IV files saved in desktop!");
ButtonManualDecrypt.Visible = true;
ButtonExit.Visible = true;
}));
}
19
View Source File : AesGcm.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3
License : GNU General Public License v3.0
Project Creator : 0xfd3
private int MaxAuthTagSize(IntPtr hAlg)
{
byte[] tagLengthsValue = GetProperty(hAlg, BCrypt.BCRYPT_AUTH_TAG_LENGTH);
return BitConverter.ToInt32(new[] { tagLengthsValue[4], tagLengthsValue[5], tagLengthsValue[6], tagLengthsValue[7] }, 0);
}
19
View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
private void WaitForConnectionCallback(IAsyncResult result)
{
if (server == null)
{
return;
}
try
{
server.EndWaitForConnection(result);
}
catch (ObjectDisposedException)
{
return;
}
byte[] replySizeBuffer = new byte[sizeof(int)];
server.ProperRead(replySizeBuffer, 0, replySizeBuffer.Length);
int messageLength = BitConverter.ToInt32(replySizeBuffer, 0);
byte[] messageBytes = new byte[messageLength];
server.ProperRead(messageBytes, 0, messageLength);
List<string> parameters = DecodeMessageBuffer(messageBytes);
if (!TryGetValue(parameters[0], "command=", out string command))
{
throw new InvalidOperationException("The first item must be a command.");
}
if (command.Equals("gmic_qt_get_max_layer_size", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the input mode.");
}
InputMode inputMode = ParseInputMode(mode);
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_get_max_layer_size' received. mode=" + inputMode.ToString());
#endif
string reply = GetMaxLayerSize(inputMode);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_get_cropped_images", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the input mode.");
}
if (!TryGetValue(parameters[2], "croprect=", out string packedCropRect))
{
throw new InvalidOperationException("The third item must be the crop rectangle.");
}
InputMode inputMode = ParseInputMode(mode);
RectangleF cropRect = GetCropRectangle(packedCropRect);
#if DEBUG
System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
"'gmic_qt_get_cropped_images' received. mode={0}, cropRect={1}",
inputMode.ToString(), cropRect.ToString()));
#endif
string reply = PrepareCroppedLayers(inputMode, cropRect);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_output_images", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the output mode.");
}
OutputMode outputMode = ParseOutputMode(mode);
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_output_images' received. mode=" + outputMode.ToString());
#endif
List<string> outputLayers = parameters.GetRange(2, parameters.Count - 2);
string reply = ProcessOutputImage(outputLayers, outputMode);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_release_shared_memory", StringComparison.Ordinal))
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_release_shared_memory' received.");
#endif
for (int i = 0; i < memoryMappedFiles.Count; i++)
{
memoryMappedFiles[i].Dispose();
}
memoryMappedFiles.Clear();
SendMessage(server, "done");
}
else if (command.Equals("gmic_qt_get_max_layer_data_length", StringComparison.Ordinal))
{
// This command is used to prevent images larger than 4GB from being used on a 32-bit version of G'MIC.
// Attempting to map an image that size into memory would cause an integer overflow when casting a 64-bit
// integer to the unsigned 32-bit size_t type.
long maxDataLength = 0;
foreach (GmicLayer layer in layers)
{
maxDataLength = Math.Max(maxDataLength, layer.Surface.Scan0.Length);
}
server.Write(BitConverter.GetBytes(sizeof(long)), 0, 4);
server.Write(BitConverter.GetBytes(maxDataLength), 0, 8);
}
// Wait for the acknowledgment that the client is done reading.
if (server.IsConnected)
{
byte[] doneMessageBuffer = new byte[4];
int bytesRead = 0;
int bytesToRead = doneMessageBuffer.Length;
do
{
int n = server.Read(doneMessageBuffer, bytesRead, bytesToRead);
bytesRead += n;
bytesToRead -= n;
} while (bytesToRead > 0 && server.IsConnected);
}
// Start a new server and wait for the next connection.
server.Dispose();
server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
server.BeginWaitForConnection(WaitForConnectionCallback, null);
}
19
View Source File : AesGcm.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3
License : GNU General Public License v3.0
Project Creator : 0xfd3
private IntPtr ImportKey(IntPtr hAlg, byte[] key, out IntPtr hKey)
{
byte[] objLength = GetProperty(hAlg, BCrypt.BCRYPT_OBJECT_LENGTH);
int keyDataSize = BitConverter.ToInt32(objLength, 0);
IntPtr keyDataBuffer = Marshal.AllocHGlobal(keyDataSize);
byte[] keyBlob = Concat(BCrypt.BCRYPT_KEY_DATA_BLOB_MAGIC, BitConverter.GetBytes(0x1), BitConverter.GetBytes(key.Length), key);
uint status = BCrypt.BCryptImportKey(hAlg, IntPtr.Zero, BCrypt.BCRYPT_KEY_DATA_BLOB, out hKey, keyDataBuffer, keyDataSize, keyBlob, keyBlob.Length, 0x0);
if (status != BCrypt.ERROR_SUCCESS)
throw new CryptographicException(string.Format("BCrypt.BCryptImportKey() failed with status code:{0}", status));
return keyDataBuffer;
}
19
View Source File : IrdParser.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static Ird Parse(byte[] content)
{
if (content == null)
throw new ArgumentNullException(nameof(content));
if (content.Length < 200)
throw new ArgumentException("Data is too small to be a valid IRD structure", nameof(content));
if (BitConverter.ToInt32(content, 0) != Ird.Magic)
using (var compressedStream = new MemoryStream(content, false))
using (var gzip = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var decompressedStream = new MemoryStream())
{
gzip.CopyTo(decompressedStream);
content = decompressedStream.ToArray();
}
if (BitConverter.ToInt32(content, 0) != Ird.Magic)
throw new FormatException("Not a valid IRD file");
var result = new Ird();
using (var stream = new MemoryStream(content, false))
using (var reader = new BinaryReader(stream, Encoding.UTF8))
{
reader.ReadInt32(); // magic
result.Version = reader.ReadByte();
result.ProductCode = Encoding.ASCII.GetString(reader.ReadBytes(9));
result.replacedleLength = reader.ReadByte();
result.replacedle = Encoding.UTF8.GetString(reader.ReadBytes(result.replacedleLength));
result.UpdateVersion = Encoding.ASCII.GetString(reader.ReadBytes(4)).Trim();
result.GameVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
result.AppVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
if (result.Version == 7)
result.Id = reader.ReadInt32();
result.HeaderLength = reader.ReadInt32();
result.Header = reader.ReadBytes(result.HeaderLength);
result.FooterLength = reader.ReadInt32();
result.Footer = reader.ReadBytes(result.FooterLength);
result.RegionCount = reader.ReadByte();
result.RegionMd5Checksums = new List<byte[]>(result.RegionCount);
for (var i = 0; i < result.RegionCount; i++)
result.RegionMd5Checksums.Add(reader.ReadBytes(16));
result.FileCount = reader.ReadInt32();
result.Files = new List<IrdFile>(result.FileCount);
for (var i = 0; i < result.FileCount; i++)
{
var file = new IrdFile();
file.Offset = reader.ReadInt64();
file.Md5Checksum = reader.ReadBytes(16);
result.Files.Add(file);
}
result.Unknown = reader.ReadInt32();
if (result.Version == 9)
result.Pic = reader.ReadBytes(115);
result.Data1 = reader.ReadBytes(16);
result.Data2 = reader.ReadBytes(16);
if (result.Version < 9)
result.Pic = reader.ReadBytes(115);
result.Uid = reader.ReadInt32();
var dataLength = reader.BaseStream.Position;
result.Crc32 = reader.ReadUInt32();
var crc32 = Crc32Algorithm.Compute(content, 0, (int)dataLength);
if (result.Crc32 != crc32)
throw new InvalidDataException($"Corrupted IRD data, expected {result.Crc32:x8}, but was {crc32:x8}");
}
return result;
}
19
View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v
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 : NetworkUtils.cs
License : MIT License
Project Creator : 1ZouLTReX1
License : MIT License
Project Creator : 1ZouLTReX1
public static int DeserializeInt(byte[] data, ref int offset)
{
int ret = BitConverter.ToInt32(data, offset);
offset += sizeof(int);
return ret;
}
19
View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v
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 : Globals.cs
License : MIT License
Project Creator : 1ZouLTReX1
License : MIT License
Project Creator : 1ZouLTReX1
public static int DeSerializeLenPrefix(byte[] data, int offset)
{
int lengthPrefix = BitConverter.ToInt32(data, offset);
return lengthPrefix;
}
19
View Source File : Common.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
{
byte[] b = new byte[4];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
Random r = new Random(BitConverter.ToInt32(b, 0));
string s = null, str = custom;
if (useNum == true) { str += "0123456789"; }
if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>[email protected][\\]^_`{|}~"; }
for (int i = 0; i < length; i++)
{
s += str.Substring(r.Next(0, str.Length - 1), 1);
}
return s;
}
19
View Source File : PlyHandler.cs
License : MIT License
Project Creator : 3DBear
License : MIT License
Project Creator : 3DBear
private static List<int> GetTriangles(byte[] bytes, PlyHeader header)
{
var toSkip = header.VertexCount * GetByteCountPerVertex(header);
var triangles = new List<int>();
int facesRead = 0;
int bytesRead = 0;
int bytesPerTriangleIndex = 4;
while (facesRead < header.FaceCount)
{
var faceIndex = toSkip + bytesRead;
var indexCount = bytes[faceIndex];
if (indexCount == 3)
{
for (int i = 0; i < indexCount; i++)
{
triangles.Add(System.BitConverter.ToInt32(bytes.SubArray(faceIndex + 1 + i * bytesPerTriangleIndex, bytesPerTriangleIndex), 0));
}
bytesRead += 1 + indexCount * bytesPerTriangleIndex;
}
else if (indexCount == 4)
{
var tmp = new List<int>();
for (int i = 0; i < indexCount; i++)
{
tmp.Add(System.BitConverter.ToInt32(bytes.SubArray(faceIndex + 1 + i * bytesPerTriangleIndex, bytesPerTriangleIndex), 0));
}
triangles.AddRange(QuadToTriangles(tmp));
bytesRead += 1 + indexCount * bytesPerTriangleIndex;
}
else
{
Debug.LogWarning("Warning: Found a face with more than 4 vertices, skipping...");
}
facesRead++;
}
return triangles;
}
19
View Source File : ASN1.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent
protected static int ReadInteger(RdpPacket packet)
{
if (packet.ReadByte() != 2)
{
throw new Exception("Data Error!");
}
int num2 = packet.ReadByte();
byte[] buffer = new byte[4];
switch (num2)
{
case 4:
packet.Read(buffer, 0, 4);
return BitConverter.ToInt32(buffer, 0);
case 3:
packet.Read(buffer, 0, 3);
return BitConverter.ToInt32(buffer, 0);
case 2:
packet.Read(buffer, 0, 2);
return BitConverter.ToInt32(buffer, 0);
}
packet.Read(buffer, 0, 1);
return BitConverter.ToInt32(buffer, 0);
}
19
View Source File : WaveFileReader.cs
License : MIT License
Project Creator : 3wz
License : MIT License
Project Creator : 3wz
public static void ReadWaveHeader(Stream stream, out WaveFormat format, out long dataChunkPosition, out int dataChunkLength, List<RiffChunk> chunks)
{
dataChunkPosition = -1;
format = null;
BinaryReader br = new BinaryReader(stream);
if (Encoding.ASCII.GetString(br.ReadBytes(4)) != "RIFF")//WaveInterop.mmioStringToFOURCC("RIFF", 0)
{
throw new FormatException("Not a WAVE file - no RIFF header");
}
uint fileSize = br.ReadUInt32(); // read the file size (minus 8 bytes)
if (Encoding.ASCII.GetString(br.ReadBytes(4)) != "WAVE")//WaveInterop.mmioStringToFOURCC("WAVE", 0)
{
throw new FormatException("Not a WAVE file - no WAVE header");
}
int dataChunkID = BitConverter.ToInt32(Encoding.UTF8.GetBytes("data"), 0); ;//WaveInterop.mmioStringToFOURCC("data", 0)
int formatChunkId = BitConverter.ToInt32(Encoding.UTF8.GetBytes("fmt "), 0); ;//WaveInterop.mmioStringToFOURCC("fmt ", 0)
dataChunkLength = 0;
// sometimes a file has more data than is specified after the RIFF header
long stopPosition = Math.Min(fileSize + 8, stream.Length);
// this -8 is so we can be sure that there are at least 8 bytes for a chunk id and length
while (stream.Position <= stopPosition - 8)
{
Int32 chunkIdentifier = br.ReadInt32();
Int32 chunkLength = br.ReadInt32();
if (chunkIdentifier == dataChunkID)
{
dataChunkPosition = stream.Position;
dataChunkLength = chunkLength;
stream.Position += chunkLength;
}
else if (chunkIdentifier == formatChunkId)
{
format = WaveFormat.FromFormatChunk(br, chunkLength);
}
else
{
// check for invalid chunk length
if (chunkLength < 0 || chunkLength > stream.Length - stream.Position)
{
Debug.replacedert(false, String.Format("Invalid chunk length {0}, pos: {1}. length: {2}",
chunkLength, stream.Position, stream.Length));
// an exception will be thrown further down if we haven't got a format and data chunk yet,
// otherwise we will tolerate this file despite it having corrupt data at the end
break;
}
if (chunks != null)
{
chunks.Add(new RiffChunk(chunkIdentifier, chunkLength, stream.Position));
}
stream.Position += chunkLength;
}
}
if (format == null)
{
throw new FormatException("Invalid WAV file - No fmt chunk found");
}
if (dataChunkPosition == -1)
{
throw new FormatException("Invalid WAV file - No data chunk found");
}
}
19
View Source File : ASN1.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent
protected static int ReadLength(RdpPacket packet, string Identifier)
{
int num;
byte[] buffer = new byte[4];
int num2 = packet.ReadByte();
switch (num2)
{
case 0x84:
buffer[3] = (byte) packet.ReadByte();
buffer[2] = (byte) packet.ReadByte();
buffer[1] = (byte) packet.ReadByte();
buffer[0] = (byte) packet.ReadByte();
num = BitConverter.ToInt32(buffer, 0);
break;
case 0x83:
buffer[2] = (byte) packet.ReadByte();
buffer[1] = (byte) packet.ReadByte();
buffer[0] = (byte) packet.ReadByte();
num = BitConverter.ToInt32(buffer, 0);
break;
case 130:
buffer[1] = (byte) packet.ReadByte();
buffer[0] = (byte) packet.ReadByte();
num = BitConverter.ToInt32(buffer, 0);
break;
case 0x81:
num = packet.ReadByte();
break;
default:
num = num2;
break;
}
m_Fixup.Add(Identifier, new Fixup(Identifier, packet.Position, num));
return num;
}
19
View Source File : RdpPacket.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent
public int ReadLittleEndian32()
{
byte[] buffer = new byte[4];
this.Read(buffer, 0, 4);
return BitConverter.ToInt32(buffer, 0);
}
19
View Source File : WaveFileReader.cs
License : MIT License
Project Creator : 3wz
License : MIT License
Project Creator : 3wz
public bool TryReadFloat(out float sampleValue)
{
sampleValue = 0.0f;
// 16 bit PCM data
if (waveFormat.BitsPerSample == 16)
{
byte[] value = new byte[2];
int read = Read(value, 0, 2);
if (read < 2)
return false;
sampleValue = (float)BitConverter.ToInt16(value, 0) / 32768f;
return true;
}
// 24 bit PCM data
else if (waveFormat.BitsPerSample == 24)
{
byte[] value = new byte[4];
int read = Read(value, 0, 3);
if (read < 3)
return false;
if (value[2] > 0x7f)
{
value[3] = 0xff;
}
else
{
value[3] = 0x00;
}
sampleValue = (float)BitConverter.ToInt32(value, 0) / (float)(0x800000);
return true;
}
// 32 bit PCM data
if (waveFormat.BitsPerSample == 32 && waveFormat.Encoding == WaveFormatEncoding.Extensible)
{
byte[] value = new byte[4];
int read = Read(value, 0, 4);
if (read < 4)
return false;
sampleValue = (float)BitConverter.ToInt32(value, 0) / ((float)(Int32.MaxValue) + 1f);
return true;
}
// IEEE float data
if (waveFormat.BitsPerSample == 32 && waveFormat.Encoding == WaveFormatEncoding.IeeeFloat)
{
byte[] value = new byte[4];
int read = Read(value, 0, 4);
if (read < 4)
return false;
sampleValue = BitConverter.ToSingle(value, 0);
return true;
}
else
{
throw new ApplicationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported");
}
}
19
View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 91Act
License : MIT License
Project Creator : 91Act
public override int ReadInt32()
{
if (endian == EndianType.BigEndian)
{
a32 = ReadBytes(4);
Array.Reverse(a32);
return BitConverter.ToInt32(a32, 0);
}
return base.ReadInt32();
}
19
View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
private static float[] Convert24BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
{
int wavSize = BitConverter.ToInt32(source, headerOffset);
headerOffset += sizeof(int);
Debug.replacedertFormat(wavSize > 0 && wavSize == dataSize, "Failed to get valid 24-bit wav size: {0} from data bytes: {1} at offset: {2}", wavSize, dataSize, headerOffset);
int x = 3; // block size = 3
int convertedSize = wavSize / x;
int maxValue = Int32.MaxValue;
float[] data = new float[convertedSize];
byte[] block = new byte[sizeof(int)]; // using a 4 byte block for copying 3 bytes, then copy bytes with 1 offset
int offset = 0;
int i = 0;
while (i < convertedSize)
{
offset = i * x + headerOffset;
Buffer.BlockCopy(source, offset, block, 1, x);
data[i] = (float)BitConverter.ToInt32(block, 0) / maxValue;
++i;
}
Debug.replacedertFormat(data.Length == convertedSize, "AudioClip .wav data is wrong size: {0} == {1}", data.Length, convertedSize);
return data;
}
19
View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static AudioClip ToAudioClip(byte[] fileBytes, int offsetSamples = 0, string name = "wav")
{
//string riff = Encoding.ASCII.GetString (fileBytes, 0, 4);
//string wave = Encoding.ASCII.GetString (fileBytes, 8, 4);
int subchunk1 = BitConverter.ToInt32(fileBytes, 16);
UInt16 audioFormat = BitConverter.ToUInt16(fileBytes, 20);
// NB: Only uncompressed PCM wav files are supported.
string formatCode = FormatCode(audioFormat);
Debug.replacedertFormat(audioFormat == 1 || audioFormat == 65534, "Detected format code '{0}' {1}, but only PCM and WaveFormatExtensable uncompressed formats are currently supported.", audioFormat, formatCode);
UInt16 channels = BitConverter.ToUInt16(fileBytes, 22);
int sampleRate = BitConverter.ToInt32(fileBytes, 24);
//int byteRate = BitConverter.ToInt32 (fileBytes, 28);
//UInt16 blockAlign = BitConverter.ToUInt16 (fileBytes, 32);
UInt16 bitDepth = BitConverter.ToUInt16(fileBytes, 34);
int headerOffset = 16 + 4 + subchunk1 + 4;
int subchunk2 = BitConverter.ToInt32(fileBytes, headerOffset);
//Debug.LogFormat ("riff={0} wave={1} subchunk1={2} format={3} channels={4} sampleRate={5} byteRate={6} blockAlign={7} bitDepth={8} headerOffset={9} subchunk2={10} filesize={11}", riff, wave, subchunk1, formatCode, channels, sampleRate, byteRate, blockAlign, bitDepth, headerOffset, subchunk2, fileBytes.Length);
float[] data;
switch (bitDepth)
{
case 8:
data = Convert8BitByteArrayToAudioClipData(fileBytes, headerOffset, subchunk2);
break;
case 16:
data = Convert16BitByteArrayToAudioClipData(fileBytes, headerOffset, subchunk2);
break;
case 24:
data = Convert24BitByteArrayToAudioClipData(fileBytes, headerOffset, subchunk2);
break;
case 32:
data = Convert32BitByteArrayToAudioClipData(fileBytes, headerOffset, subchunk2);
break;
default:
throw new Exception(bitDepth + " bit depth is not supported.");
}
AudioClip audioClip = AudioClip.Create(name, data.Length, (int)channels, sampleRate, false);
audioClip.SetData(data, 0);
return audioClip;
}
19
View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
private static float[] Convert32BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
{
int wavSize = BitConverter.ToInt32(source, headerOffset);
headerOffset += sizeof(int);
Debug.replacedertFormat(wavSize > 0 && wavSize == dataSize, "Failed to get valid 32-bit wav size: {0} from data bytes: {1} at offset: {2}", wavSize, dataSize, headerOffset);
int x = sizeof(float); // block size = 4
int convertedSize = wavSize / x;
Int32 maxValue = Int32.MaxValue;
float[] data = new float[convertedSize];
int offset = 0;
int i = 0;
while (i < convertedSize)
{
offset = i * x + headerOffset;
data[i] = (float)BitConverter.ToInt32(source, offset) / maxValue;
++i;
}
Debug.replacedertFormat(data.Length == convertedSize, "AudioClip .wav data is wrong size: {0} == {1}", data.Length, convertedSize);
return data;
}
19
View Source File : NetworkBitConverter.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public static int ToInt32(Span<byte> buffer, bool littleEndian = false)
{
if (!littleEndian)
{
buffer.Slice(0, sizeof(int)).Reverse();
}
return BitConverter.ToInt32(buffer);
}
19
View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public bool TryDecodeData(Span<byte> buffer, out int consumed)
{
v1 = BitConverter.ToDouble(buffer);
v2 = BitConverter.ToInt32(buffer.Slice(sizeof(double)));
consumed = sizeof(double) + sizeof(int);
return true;
}
19
View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
private static float[] Convert8BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
{
int wavSize = BitConverter.ToInt32(source, headerOffset);
headerOffset += sizeof(int);
Debug.replacedertFormat(wavSize > 0 && wavSize == dataSize, "Failed to get valid 8-bit wav size: {0} from data bytes: {1} at offset: {2}", wavSize, dataSize, headerOffset);
float[] data = new float[wavSize];
sbyte maxValue = sbyte.MaxValue;
int i = 0;
while (i < wavSize)
{
data[i] = (float)source[i] / maxValue;
++i;
}
return data;
}
19
View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
private static float[] Convert16BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
{
int wavSize = BitConverter.ToInt32(source, headerOffset);
headerOffset += sizeof(int);
Debug.replacedertFormat(wavSize > 0 && wavSize == dataSize, "Failed to get valid 16-bit wav size: {0} from data bytes: {1} at offset: {2}", wavSize, dataSize, headerOffset);
int x = sizeof(Int16); // block size = 2
int convertedSize = wavSize / x;
float[] data = new float[convertedSize];
Int16 maxValue = Int16.MaxValue;
int offset = 0;
int i = 0;
while (i < convertedSize)
{
offset = i * x + headerOffset;
data[i] = (float)BitConverter.ToInt16(source, offset) / maxValue;
++i;
}
Debug.replacedertFormat(data.Length == convertedSize, "AudioClip .wav data is wrong size: {0} == {1}", data.Length, convertedSize);
return data;
}
19
View Source File : ConnectClient.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public byte[] ReceiveBytes()
{
//кол-во байт в начале в которых передается длинна сообщения
int Int32Length = 4;
//длина передаваемого сообщения (принимается в первых 4 байтах (константа Int32Length))
int lenghtAllMessageByte;
CurrentReceiveRequestLength = Int32Length;
CurrentRequestStart = DateTime.UtcNow;
//оставляем кол-во байт к последней отправке, чтобы ждать не только приема этих 4, но и окончания отправки тех CurrentSendRequestLength
if ((CurrentRequestStart - LastSend).TotalSeconds > 1d) CurrentSendRequestLength = 0;
try
{
byte[] receiveBuffer = ReceiveBytes(Int32Length);
lenghtAllMessageByte = BitConverter.ToInt32(receiveBuffer, 0);
if (lenghtAllMessageByte == 0) return new byte[0];
CurrentSendRequestLength = 0;
CurrentReceiveRequestLength = lenghtAllMessageByte;
CurrentRequestStart = DateTime.UtcNow;
receiveBuffer = ReceiveBytes(lenghtAllMessageByte);
return receiveBuffer;
}
finally
{
CurrentRequestStart = DateTime.MinValue;
}
}
19
View Source File : ModelFileInfo.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public override int GetHashCode()
{
if (Hash == null || Hash.Length < 8)
{
return 0;
}
// переводит первые 4 байта в int
return BitConverter.ToInt32(Hash, 0);
}
19
View Source File : ClientMessageParser.cs
License : MIT License
Project Creator : Abaudat
License : MIT License
Project Creator : Abaudat
public void ParseMessage(byte[] message)
{
byte[] size = new byte[sizeof(int)];
Buffer.BlockCopy(message, 0, size, 0, sizeof(int));
byte[] data = new byte[BitConverter.ToInt32(size, 0)];
Buffer.BlockCopy(message, sizeof(int) + 1, data, 0, data.Length);
switch (message[sizeof(int)]) // Add cases to this switch for all different types of message the client can receive.
{
case (byte)NetworkingFlags.Flags.DEBUG_MESSAGE:
OnDebugMessage(data);
break;
default:
Debug.LogWarning("WARNING: Unknown byte flag " + message[sizeof(int)] + " .");
break;
}
}
19
View Source File : ServerMessageParser.cs
License : MIT License
Project Creator : Abaudat
License : MIT License
Project Creator : Abaudat
public void ParseMessage(byte[] message, int connectionId)
{
byte[] size = new byte[sizeof(int)];
Buffer.BlockCopy(message, 0, size, 0, sizeof(int));
byte[] data = new byte[BitConverter.ToInt32(size, 0)];
Buffer.BlockCopy(message, sizeof(int) + 1, data, 0, data.Length);
switch (message[sizeof(int)]) // Add cases to this switch for all different types of message the server can receive.
{
case (byte)NetworkingFlags.Flags.DEBUG_MESSAGE:
OnDebugMessage(data, connectionId);
break;
default:
Debug.LogWarning("WARNING: Unknown byte flag " + message[sizeof(int)] + " .");
break;
}
}
19
View Source File : EndianBitConverter.cs
License : Microsoft Public License
Project Creator : abfo
License : Microsoft Public License
Project Creator : abfo
public static int ToInt32(byte[] value, int startIndex, ProvidedOrder order)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if ((startIndex + sizeof(int)) > value.Length)
{
throw new ArgumentException("startIndex invalid (not enough space in value to extract an integer", "startIndex");
}
if (BitConverter.IsLittleEndian && (order == ProvidedOrder.Big))
{
byte[] toConvert = new byte[sizeof(int)];
Array.Copy(value, startIndex, toConvert, 0, sizeof(int));
Array.Reverse(toConvert);
return BitConverter.ToInt32(toConvert, 0);
}
else
{
return BitConverter.ToInt32(value, startIndex);
}
}
19
View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
int UnpackInt32(byte[] buf, ref int offset)
{
int value = BitConverter.ToInt32(buf, offset);
offset += 4;
return value;
}
19
View Source File : Host.cs
License : MIT License
Project Creator : acandylevey
License : MIT License
Project Creator : acandylevey
private JObject Read()
{
Log.LogMessage("Waiting for Data");
Stream stdin = Console.OpenStandardInput();
byte[] lengthBytes = new byte[4];
stdin.Read(lengthBytes, 0, 4);
char[] buffer = new char[BitConverter.ToInt32(lengthBytes, 0)];
using (StreamReader reader = new StreamReader(stdin))
if (reader.Peek() >= 0)
reader.Read(buffer, 0, buffer.Length);
return JsonConvert.DeserializeObject<JObject>(new string(buffer));
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
public static string RandomString(int length)
{
var b = new byte[4];
new RNGCryptoServiceProvider().GetBytes(b);
var r = new Random(BitConverter.ToInt32(b, 0));
var ret = string.Empty;
const string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var i = 0; i < length; i++)
ret += str.Substring(r.Next(0, str.Length - 1), 1);
return ret;
}
19
View Source File : StreamString.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public async Task<Int32> ReadInt32Async(CancellationToken cancellationToken)
{
byte[] readBytes = new byte[sizeof(Int32)];
int dataread = 0;
while (sizeof(Int32) - dataread > 0 && (!cancellationToken.IsCancellationRequested))
{
Task<int> op = _ioStream.ReadAsync(readBytes, dataread, sizeof(Int32) - dataread, cancellationToken);
int newData = 0;
newData = await op.WithCancellation(cancellationToken);
dataread += newData;
if (0 == newData)
{
await Task.Delay(100, cancellationToken);
}
}
cancellationToken.ThrowIfCancellationRequested();
return BitConverter.ToInt32(readBytes, 0);
}
19
View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public static int GetInt32(byte[] data, int index = 0)
=> BitConverter.ToInt32(data, index);
19
View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public static string[] GetStringArray(int index, int length, byte[] data)
{
List<string> strings = new List<string>();
for (int position = index; position < index + length;)
{
var stringLength = BitConverter.ToInt32(data, position);
var indexpos = position + 4;
position = position + 4 + stringLength;
strings.Add(GetString(data, indexpos, stringLength - 2)); //minus null-terminator
}
return strings.ToArray();
}
19
View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public static string PrettyPrintStringArrayFromRaw(byte[] dataRaw)
{
StringBuilder stringBuilder = new StringBuilder();
for (int position = 0; position < dataRaw.Length;)
{
var stringLength = BitConverter.ToInt32(dataRaw, position);
var index = position + 4;
position = position + 4 + stringLength;
stringBuilder.Append("[ \"" + GetString(dataRaw, index, stringLength).ReplaceMultilineWithSymbols() + "\" ]");
if (position != dataRaw.Length)
stringBuilder.Append(", ");
}
return stringBuilder.ToString();
}
19
View Source File : FsBufferedReaderWriter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected int ReadInt()
{
var raw = new byte[sizeof(int)];
this.fileStream.Read(raw, 0, raw.Length);
var value = BitConverter.ToInt32(raw, 0);
return value;
}
19
View Source File : BytesReader.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
public Int32 ReadInt() {
var bytes = ReadBytes(4);
EndianUtility.EndianCorrection(bytes);
return BitConverter.ToInt32(bytes, 0);
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
public static int ToInt(this byte[] bytes) {
return BitConverter.ToInt32(bytes, 0);
}
19
View Source File : testUtil.cs
License : Apache License 2.0
Project Creator : advancer68
License : Apache License 2.0
Project Creator : advancer68
public static int Unpack2Int(this byte[] self, int indx)
{
return BitConverter.ToInt32(self, indx);
}
19
View Source File : BytePacker.cs
License : Apache License 2.0
Project Creator : advancer68
License : Apache License 2.0
Project Creator : advancer68
public void Recv(byte[] buff)
{
cache.AddRange(buff);
while (true)
{
if (curPkgSize < 0)// if not pkg size
{
if (cache.Count > pkgLengthByteSize)
{
//get pkg size
cache.CopyTo(0, pkgLengthBytes, 0, pkgLengthByteSize);
cache.RemoveRange(0, pkgLengthByteSize);
curPkgSize = BitConverter.ToInt32(pkgLengthBytes, 0);
}
else
{
break;
}
}
if (cache.Count >= curPkgSize)
{//get pkg data
var pkgData = new byte[curPkgSize];
cache.CopyTo(0, pkgData, 0, pkgData.Length);
cache.RemoveRange(0, curPkgSize);
func.Invoke(pkgData);
//reset pkg size
curPkgSize = -1;
}
else
{
break;
}
}
}
19
View Source File : ByteBuf.cs
License : Apache License 2.0
Project Creator : advancer68
License : Apache License 2.0
Project Creator : advancer68
public int GetInt32(int index)
{
if (CanRead(4))
{
return BitConverter.ToInt32(data, RawReadIndex(index));
}
return 0;
}
19
View Source File : StringCompressor.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static string DecompressString(string compressedText)
{
byte[] array = Convert.FromBase64String(compressedText);
string @string;
using (MemoryStream memoryStream = new MemoryStream())
{
int num = BitConverter.ToInt32(array, 0);
memoryStream.Write(array, 4, array.Length - 4);
byte[] array2 = new byte[num];
memoryStream.Position = 0L;
using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
gzipStream.Read(array2, 0, array2.Length);
}
@string = Encoding.UTF8.GetString(array2);
}
return @string;
}
19
View Source File : ByteExtensions.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public static int ToInt32(this byte[] bytes, bool bigEndian)
{
var needReverse = !bigEndian ^ BitConverter.IsLittleEndian;
return BitConverter.ToInt32(needReverse ? bytes.Reverse().ToArray() : bytes, 0);
}
19
View Source File : ExtensionTests.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
[Fact]
public void NumericExtensions_ToBytes_For_int()
{
int number = -2;
var bigEndianBytes = number.ToBytes(true);
((int)bigEndianBytes.Last()).ShouldBe(254);
var numberFromBigEndianBytes = BitConverter.ToInt32(BitConverter.IsLittleEndian ? bigEndianBytes.Reverse().ToArray() : bigEndianBytes);
numberFromBigEndianBytes.ShouldBe(number);
var littleEndianBytes = number.ToBytes(false);
((int)littleEndianBytes.Last()).ShouldBe(255);
numberFromBigEndianBytes = BitConverter.ToInt32(BitConverter.IsLittleEndian ? littleEndianBytes: littleEndianBytes.Reverse().ToArray());
numberFromBigEndianBytes.ShouldBe(number);
}
19
View Source File : CRTInjection.cs
License : Apache License 2.0
Project Creator : aequabit
License : Apache License 2.0
Project Creator : aequabit
public override IntPtr[] InjectAll(string[] dllPaths, IntPtr hProcess)
{
this.ClearErrors();
if (hProcess.IsNull() || hProcess.Compare(-1L))
{
throw new ArgumentOutOfRangeException("hProcess", "Invalid process handle specified.");
}
try
{
IntPtr zero = IntPtr.Zero;
IntPtr ptr = this.CreateMultiLoadStub(dllPaths, hProcess, out zero, 0);
IntPtr[] ptrArray = null;
if (!ptr.IsNull())
{
try
{
if (WinAPI.RunThread(hProcess, ptr, 0, 0x2710) == uint.MaxValue)
{
throw new Exception("Error occurred while executing remote thread.");
}
byte[] buffer = WinAPI.ReadRemoteMemory(hProcess, zero, ((uint) dllPaths.Length) << 2);
if (buffer == null)
{
throw new InvalidOperationException("Unable to read from the remote process.");
}
ptrArray = new IntPtr[dllPaths.Length];
for (int i = 0; i < ptrArray.Length; i++)
{
ptrArray[i] = new IntPtr(BitConverter.ToInt32(buffer, i << 2));
}
}
finally
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, ptr, 0, 0x8000);
}
}
return ptrArray;
}
catch (Exception exception)
{
this.SetLastError(exception);
return null;
}
}
19
View Source File : ThreadHijack.cs
License : Apache License 2.0
Project Creator : aequabit
License : Apache License 2.0
Project Creator : aequabit
public override IntPtr[] InjectAll(string[] dllPaths, IntPtr hProcess)
{
Exception exception;
this.ClearErrors();
try
{
if (hProcess.IsNull() || hProcess.Compare(-1L))
{
throw new ArgumentException("Invalid process handle.", "hProcess");
}
int processId = WinAPI.GetProcessId(hProcess);
if (processId == 0)
{
throw new ArgumentException("Provided handle doesn't have sufficient permissions to inject", "hProcess");
}
Process processById = Process.GetProcessById(processId);
if (processById.Threads.Count == 0)
{
throw new Exception("Target process has no targetable threads to hijack.");
}
ProcessThread thread = SelectOptimalThread(processById);
IntPtr ptr = WinAPI.OpenThread(0x1a, false, thread.Id);
if (ptr.IsNull() || ptr.Compare(-1L))
{
throw new Exception("Unable to obtain a handle for the remote thread.");
}
IntPtr zero = IntPtr.Zero;
IntPtr lpAddress = IntPtr.Zero;
IntPtr ptr4 = this.CreateMultiLoadStub(dllPaths, hProcess, out zero, 1);
IntPtr[] ptrArray = null;
if (!ptr4.IsNull())
{
if (WinAPI.SuspendThread(ptr) == uint.MaxValue)
{
throw new Exception("Unable to suspend the remote thread");
}
try
{
uint lpNumberOfBytesRead = 0;
WinAPI.CONTEXT pContext = new WinAPI.CONTEXT {
ContextFlags = 0x10001
};
if (!WinAPI.GetThreadContext(ptr, ref pContext))
{
throw new InvalidOperationException("Cannot get the remote thread's context");
}
byte[] array = REDIRECT_STUB;
IntPtr ptr5 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) array.Length, 0x3000, 0x40);
if (ptr5.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process.");
}
BitConverter.GetBytes(ptr4.Subtract(ptr5.Add(((long) 7L))).ToInt32()).CopyTo(array, 3);
BitConverter.GetBytes((uint) (pContext.Eip - ((uint) ptr5.Add(((long) array.Length)).ToInt32()))).CopyTo(array, (int) (array.Length - 4));
if (!(WinAPI.WriteProcessMemory(hProcess, ptr5, array, array.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == array.Length)))
{
throw new InvalidOperationException("Unable to write stub to the remote process.");
}
pContext.Eip = (uint) ptr5.ToInt32();
WinAPI.SetThreadContext(ptr, ref pContext);
}
catch (Exception exception1)
{
exception = exception1;
this.SetLastError(exception);
ptrArray = null;
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, ptr4, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, lpAddress, 0, 0x8000);
}
WinAPI.ResumeThread(ptr);
if (this.GetLastError() == null)
{
Thread.Sleep(100);
ptrArray = new IntPtr[dllPaths.Length];
byte[] buffer2 = WinAPI.ReadRemoteMemory(hProcess, zero, ((uint) dllPaths.Length) << 2);
if (buffer2 != null)
{
for (int i = 0; i < ptrArray.Length; i++)
{
ptrArray[i] = Win32Ptr.Create((long) BitConverter.ToInt32(buffer2, i << 2));
}
}
}
WinAPI.CloseHandle(ptr);
}
return ptrArray;
}
catch (Exception exception2)
{
exception = exception2;
this.SetLastError(exception);
return null;
}
}
19
View Source File : Server.cs
License : Apache License 2.0
Project Creator : aequabit
License : Apache License 2.0
Project Creator : aequabit
private void HandleRead(byte[] data, int index, int length)
{
if (ReadIndex >= ReadBuffer.Length)
{
ReadIndex = 0;
if (data.Length < 4)
{
OnExceptionThrown(new Exception("Missing or corrupt packet header."));
Disconnect();
return;
}
int PacketSize = BitConverter.ToInt32(data, index);
if (PacketSize > _MaxPacketSize)
{
OnExceptionThrown(new Exception("Packet size exceeds MaxPacketSize."));
Disconnect();
return;
}
Array.Resize(ref ReadBuffer, PacketSize);
index += 4;
}
int Read = Math.Min(ReadBuffer.Length - ReadIndex, length - index);
Buffer.BlockCopy(data, index, ReadBuffer, ReadIndex, Read);
ReadIndex += Read;
OnReadProgressChanged((ReadIndex / ReadBuffer.Length) * 100, ReadIndex, ReadBuffer.Length);
if (ReadIndex >= ReadBuffer.Length)
{
OnReadPacket(ReadBuffer);
}
if (Read < (length - index))
{
HandleRead(data, index + Read, length);
}
}
19
View Source File : StandardInjectionMethod.cs
License : Apache License 2.0
Project Creator : aequabit
License : Apache License 2.0
Project Creator : aequabit
public override bool[] UnloadAll(IntPtr[] hModules, IntPtr hProcess)
{
bool[] flagArray2;
this.ClearErrors();
IntPtr zero = IntPtr.Zero;
IntPtr ptr = IntPtr.Zero;
IntPtr ptr3 = IntPtr.Zero;
try
{
int num2;
uint lpNumberOfBytesRead = 0;
IntPtr procAddress = WinAPI.GetProcAddress(WinAPI.GetModuleHandleA("kernel32.dll"), "FreeLibrary");
if (procAddress.IsNull())
{
throw new Exception("Unable to find necessary function entry points in the remote process");
}
zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, ((uint) hModules.Length) << 2, 0x3000, 4);
ptr = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) ((hModules.Length + 1) << 2), 0x3000, 4);
ptr3 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) MULTIUNLOAD_STUB.Length, 0x3000, 0x40);
if ((zero.IsNull() || ptr.IsNull()) || ptr3.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process");
}
byte[] array = new byte[(hModules.Length + 1) << 2];
for (num2 = 0; num2 < hModules.Length; num2++)
{
BitConverter.GetBytes(hModules[num2].ToInt32()).CopyTo(array, (int) (num2 << 2));
}
WinAPI.WriteProcessMemory(hProcess, ptr, array, array.Length, out lpNumberOfBytesRead);
byte[] buffer2 = (byte[]) MULTIUNLOAD_STUB.Clone();
BitConverter.GetBytes(ptr.ToInt32()).CopyTo(buffer2, 7);
BitConverter.GetBytes(zero.ToInt32()).CopyTo(buffer2, 15);
BitConverter.GetBytes(procAddress.Subtract(ptr3.Add(((long) 0x38L))).ToInt32()).CopyTo(buffer2, 0x34);
if (!(WinAPI.WriteProcessMemory(hProcess, ptr3, buffer2, buffer2.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == buffer2.Length)))
{
throw new InvalidOperationException("Unable to write the function stub to the remote process.");
}
if (WinAPI.RunThread(hProcess, ptr3, 0, 0x3e8) == uint.MaxValue)
{
throw new InvalidOperationException("Error occurred when running remote function stub.");
}
byte[] buffer3 = WinAPI.ReadRemoteMemory(hProcess, zero, ((uint) hModules.Length) << 2);
if (buffer3 == null)
{
throw new Exception("Unable to read results from the remote process.");
}
bool[] flagArray = new bool[hModules.Length];
for (num2 = 0; num2 < flagArray.Length; num2++)
{
flagArray[num2] = BitConverter.ToInt32(buffer3, num2 << 2) != 0;
}
flagArray2 = flagArray;
}
catch (Exception exception)
{
this.SetLastError(exception);
flagArray2 = null;
}
finally
{
WinAPI.VirtualFreeEx(hProcess, ptr3, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, ptr, 0, 0x8000);
}
return flagArray2;
}
19
View Source File : WinAPI.cs
License : Apache License 2.0
Project Creator : aequabit
License : Apache License 2.0
Project Creator : aequabit
public static IntPtr ReadRemotePointer(IntPtr hProcess, IntPtr pData)
{
IntPtr zero = IntPtr.Zero;
if (!hProcess.IsNull() && !pData.IsNull())
{
byte[] buffer = null;
buffer = ReadRemoteMemory(hProcess, pData, (uint) IntPtr.Size);
if (buffer != null)
{
zero = new IntPtr(BitConverter.ToInt32(buffer, 0));
}
}
return zero;
}
See More Examples