Here are the examples of the csharp api System.BitConverter.GetBytes(long) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
634 Examples
19
Source : ImageFileCache.cs
with Microsoft Public License
from ClemensFischer
with Microsoft Public License
from ClemensFischer
private static void WriteExpiration(Stream stream, DateTime expiration)
{
stream.Write(Encoding.ASCII.GetBytes(expiresTag), 0, 8);
stream.Write(BitConverter.GetBytes(expiration.Ticks), 0, 8);
}
19
Source : ImageFileCache.cs
with Microsoft Public License
from ClemensFischer
with Microsoft Public License
from ClemensFischer
private static async Task WriteExpirationAsync(Stream stream, DateTime expiration)
{
await stream.WriteAsync(Encoding.ASCII.GetBytes(expiresTag), 0, 8);
await stream.WriteAsync(BitConverter.GetBytes(expiration.Ticks), 0, 8);
}
19
Source : TotpHelper.cs
with MIT License
from cloudnative-netcore
with MIT License
from cloudnative-netcore
private static int ComputeTotp(HashAlgorithm hashAlgorithm, ulong timestepNumber, string modifier)
{
// # of 0's = length of pin
const int Mod = 1000000;
// See https://tools.ietf.org/html/rfc4226
// We can add an optional modifier
var timestepAsBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((long)timestepNumber));
var hash = hashAlgorithm.ComputeHash(ApplyModifier(timestepAsBytes, modifier));
// Generate DT string
var offset = hash[hash.Length - 1] & 0xf;
Debug.replacedert(offset + 4 < hash.Length);
var binaryCode = ((hash[offset] & 0x7f) << 24)
| ((hash[offset + 1] & 0xff) << 16)
| ((hash[offset + 2] & 0xff) << 8)
| (hash[offset + 3] & 0xff);
return binaryCode % Mod;
}
19
Source : SevenZipWrapper.cs
with MIT License
from CmlLib
with MIT License
from CmlLib
public static void CompressFileLZMA(string inFile, string outFile)
{
SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();
FileStream input = new FileStream(inFile, FileMode.Open);
FileStream output = new FileStream(outFile, FileMode.Create);
// Write the encoder properties
coder.WriteCoderProperties(output);
// Write the decompressed file size.
output.Write(BitConverter.GetBytes(input.Length), 0, 8);
// Encode the file.
coder.Code(input, output, input.Length, -1, null);
output.Flush();
output.Close();
}
19
Source : SequentialGuidGenerator.cs
with GNU Lesser General Public License v3.0
from cnAbp
with GNU Lesser General Public License v3.0
from cnAbp
public Guid Create(SequentialGuidType guidType)
{
// We start with 16 bytes of cryptographically strong random data.
var randomBytes = new byte[10];
RandomNumberGenerator.Locking(r => r.GetBytes(randomBytes));
// An alternate method: use a normally-created GUID to get our initial
// random data:
// byte[] randomBytes = Guid.NewGuid().ToByteArray();
// This is faster than using RNGCryptoServiceProvider, but I don't
// recommend it because the .NET Framework makes no guarantee of the
// randomness of GUID data, and future versions (or different
// implementations like Mono) might use a different method.
// Now we have the random basis for our GUID. Next, we need to
// create the six-byte block which will be our timestamp.
// We start with the number of milliseconds that have elapsed since
// DateTime.MinValue. This will form the timestamp. There's no use
// being more specific than milliseconds, since DateTime.Now has
// limited resolution.
// Using millisecond resolution for our 48-bit timestamp gives us
// about 5900 years before the timestamp overflows and cycles.
// Hopefully this should be sufficient for most purposes. :)
long timestamp = DateTime.UtcNow.Ticks / 10000L;
// Then get the bytes
byte[] timestampBytes = BitConverter.GetBytes(timestamp);
// Since we're converting from an Int64, we have to reverse on
// little-endian systems.
if (BitConverter.IsLittleEndian)
{
Array.Reverse(timestampBytes);
}
byte[] guidBytes = new byte[16];
switch (guidType)
{
case SequentialGuidType.Sequentialreplacedtring:
case SequentialGuidType.SequentialAsBinary:
// For string and byte-array version, we copy the timestamp first, followed
// by the random data.
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);
Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10);
// If formatting as a string, we have to compensate for the fact
// that .NET regards the Data1 and Data2 block as an Int32 and an Int16,
// respectively. That means that it switches the order on little-endian
// systems. So again, we have to reverse.
if (guidType == SequentialGuidType.Sequentialreplacedtring && BitConverter.IsLittleEndian)
{
Array.Reverse(guidBytes, 0, 4);
Array.Reverse(guidBytes, 4, 2);
}
break;
case SequentialGuidType.SequentialAtEnd:
// For sequential-at-the-end versions, we copy the random data first,
// followed by the timestamp.
Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
break;
}
return new Guid(guidBytes);
}
19
Source : Thread_Info.cs
with MIT License
from Coalfire-Research
with MIT License
from Coalfire-Research
internal ErcResult<List<byte[]>> BuildSehChain()
{
ErcResult<List<byte[]>> sehList = new ErcResult<List<byte[]>>(ThreadCore);
sehList.ReturnValue = new List<byte[]>();
if (Teb.Equals(default(TEB)))
{
sehList.Error = new Exception("Error: TEB structure for this thread has not yet been populated. Call PopulateTEB first");
return sehList;
}
if(Teb.CurrentSehFrame == IntPtr.Zero)
{
sehList.Error = new Exception("Error: No SEH chain has been generated yet. An SEH chain will not be generated until a crash occurs.");
return sehList;
}
byte[] sehEntry;
byte[] sehFinal;
int arraySize = 0;
if(X64 == MachineType.x64)
{
arraySize = 8;
sehEntry = new byte[arraySize];
sehFinal = new byte[arraySize];
sehEntry = BitConverter.GetBytes((long)Teb.CurrentSehFrame);
}
else
{
arraySize = 4;
sehEntry = new byte[arraySize];
sehFinal = new byte[arraySize];
sehEntry = BitConverter.GetBytes((int)Teb.CurrentSehFrame);
}
for (int i = 0; i < sehFinal.Length; i++)
{
sehFinal[i] = 0xFF;
}
byte[] prevSEH = new byte[] { 0xFF };
string pattern_standard = File.ReadAllText(ThreadCore.PatternStandardPath);
string pattern_extended = File.ReadAllText(ThreadCore.PatternExtendedPath);
while (!sehEntry.SequenceEqual(sehFinal))
{
byte[] reversedSehEntry = new byte[arraySize];
int ret = 0;
if(X64 == MachineType.x64)
{
ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt64(sehEntry, 0), sehEntry, arraySize, out int retInt);
}
else
{
ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt32(sehEntry, 0), sehEntry, arraySize, out int retInt);
}
if(ret != 0 && ret != 1)
{
ERCException e = new ERCException("System error: An error occured when executing ReadProcessMemory\n Process Handle = 0x"
+ ThreadProcess.ProcessHandle.ToString("X") + " TEB Current Seh = 0x" + Teb.CurrentSehFrame.ToString("X") +
" Return value = " + ret + Environment.NewLine + "Win32Exception: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
sehList.Error = e;
sehList.LogEvent();
return sehList;
}
for(int i = 0; i < sehEntry.Length; i++)
{
reversedSehEntry[i] = sehEntry[i];
}
Array.Reverse(reversedSehEntry, 0, reversedSehEntry.Length);
if (prevSEH.SequenceEqual(reversedSehEntry))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
else if (!sehEntry.SequenceEqual(sehFinal) && !sehList.ReturnValue.Contains(reversedSehEntry))
{
sehList.ReturnValue.Add(reversedSehEntry);
}
if (pattern_standard.Contains(Encoding.Unicode.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.Unicode.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
if (pattern_standard.Contains(Encoding.ASCII.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.ASCII.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
if (pattern_standard.Contains(Encoding.UTF32.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.UTF32.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
if (pattern_standard.Contains(Encoding.UTF7.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.UTF7.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
if (pattern_standard.Contains(Encoding.UTF8.GetString(reversedSehEntry)) ||
pattern_extended.Contains(Encoding.UTF8.GetString(reversedSehEntry)))
{
sehEntry = new byte[sehFinal.Length];
Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
}
prevSEH = new byte[reversedSehEntry.Length];
Array.Copy(reversedSehEntry, 0, prevSEH, 0, reversedSehEntry.Length);
}
SehChain = new List<byte[]>(sehList.ReturnValue.ToList());
return sehList;
}
19
Source : Generic.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr
with BSD 3-Clause "New" or "Revised" License
from cobbr
public static string GetAPIHash(string APIName, long Key)
{
byte[] data = Encoding.UTF8.GetBytes(APIName.ToLower());
byte[] kbytes = BitConverter.GetBytes(Key);
using (HMACMD5 hmac = new HMACMD5(kbytes))
{
byte[] bHash = hmac.ComputeHash(data);
return BitConverter.ToString(bHash).Replace("-", "");
}
}
19
Source : GuidUtil.cs
with MIT License
from cocosip
with MIT License
from cocosip
public static Guid NewSequentialGuid()
{
// This code was not reviewed to guarantee uniqueness under most conditions, nor completely optimize for avoiding
// page splits in SQL Server when doing inserts from multiple hosts, so do not re-use in production systems.
var guidBytes = Guid.NewGuid().ToByteArray();
// get the milliseconds since Jan 1 1970
byte[] sequential = BitConverter.GetBytes(DateTime.Now.Ticks / 10000L - EpochMilliseconds);
// discard the 2 most significant bytes, as we only care about the milliseconds increasing, but the highest ones
// should be 0 for several thousand years to come (non-issue).
if (BitConverter.IsLittleEndian)
{
guidBytes[10] = sequential[5];
guidBytes[11] = sequential[4];
guidBytes[12] = sequential[3];
guidBytes[13] = sequential[2];
guidBytes[14] = sequential[1];
guidBytes[15] = sequential[0];
}
else
{
Buffer.BlockCopy(sequential, 2, guidBytes, 10, 6);
}
return new Guid(guidBytes);
}
19
Source : ByteBufferUtil.cs
with MIT License
from cocosip
with MIT License
from cocosip
public static byte[] EncodeDateTime(DateTime dateTime)
{
return BitConverter.GetBytes(dateTime.Ticks);
}
19
Source : ByteBufferUtilTest.cs
with MIT License
from cocosip
with MIT License
from cocosip
[Fact]
public void Encode_Test()
{
var r1 = ByteBufferUtil.EncodeString("hellow");
var sourceBytes1 = Encoding.UTF8.GetBytes("hellow");
var dest1 = new byte[4];
Array.Copy(r1, dest1, dest1.Length);
replacedert.Equal(sourceBytes1.Length, BitConverter.ToInt32(dest1));
var r2 = ByteBufferUtil.DecodeString(r1, 0, out int len);
replacedert.Equal("hellow", r2);
var short_1 = BitConverter.GetBytes((short)1);
var int_1 = BitConverter.GetBytes(2);
var long_1 = BitConverter.GetBytes(3L);
var combineByte1 = ByteBufferUtil.Combine(short_1, int_1, long_1);
var startOffset = 0;
var short_2 = ByteBufferUtil.DecodeShort(combineByte1, startOffset, out startOffset);
var int_2 = ByteBufferUtil.DecodeInt(combineByte1, startOffset, out startOffset);
var long_2 = ByteBufferUtil.DecodeLong(combineByte1, startOffset, out startOffset);
replacedert.Equal(1, short_2);
replacedert.Equal(2, int_2);
replacedert.Equal(3, long_2);
var d1 = new DateTime(2019, 1, 1, 1, 1, 1);
var b1 = ByteBufferUtil.EncodeDateTime(d1);
var d2 = ByteBufferUtil.DecodeDateTime(b1, 0, out int n1);
replacedert.Equal(d1, d2);
var byte1 = new byte[] { 1, 2, 3 };
var b2 = ByteBufferUtil.EncodeBytes(byte1);
var byte2 = ByteBufferUtil.DecodeBytes(b2, 0, out int n2);
replacedert.Equal(byte1, byte2);
}
19
Source : GuidHelper.cs
with Apache License 2.0
from Coldairarrow
with Apache License 2.0
from Coldairarrow
public static Guid NewGuid(SequentialGuidType guidType = SequentialGuidType.AtEnd)
{
byte[] randomBytes = new byte[10];
_randomGenerator.GetBytes(randomBytes);
long timestamp = DateTime.UtcNow.Ticks / 10000L;
// Then get the bytes
byte[] timestampBytes = BitConverter.GetBytes(timestamp);
// Since we're converting from an Int64, we have to reverse on
// little-endian systems.
if (BitConverter.IsLittleEndian)
{
Array.Reverse(timestampBytes);
}
byte[] guidBytes = new byte[16];
switch (guidType)
{
case SequentialGuidType.AtBegin:
// For string and byte-array version, we copy the timestamp first, followed
// by the random data.
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);
Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10);
// If formatting as a string, we have to compensate for the fact
// that .NET regards the Data1 and Data2 block as an Int32 and an Int16,
// respectively. That means that it switches the order on little-endian
// systems. So again, we have to reverse.
if (guidType == SequentialGuidType.AtBegin && BitConverter.IsLittleEndian)
{
Array.Reverse(guidBytes, 0, 4);
Array.Reverse(guidBytes, 4, 2);
}
break;
case SequentialGuidType.AtEnd:
// For sequential-at-the-end versions, we copy the random data first,
// followed by the timestamp.
Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
break;
}
return new Guid(guidBytes);
}
19
Source : Program.cs
with GNU General Public License v3.0
from Complexicon
with GNU General Public License v3.0
from Complexicon
public void Write(long BasePTR, int[] offset, long Value) => Write(BasePTR, offset, BitConverter.GetBytes(Value));
19
Source : SavWav.cs
with MIT License
from corycorvus
with MIT License
from corycorvus
static void WriteHeader(FileStream fileStream, AudioClip clip)
{
var hz = clip.frequency;
var channels = clip.channels;
var samples = clip.samples;
fileStream.Seek(0, SeekOrigin.Begin);
Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
fileStream.Write(riff, 0, 4);
Byte[] chunkSize = BitConverter.GetBytes(fileStream.Length - 8);
fileStream.Write(chunkSize, 0, 4);
Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
fileStream.Write(wave, 0, 4);
Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
fileStream.Write(fmt, 0, 4);
Byte[] subChunk1 = BitConverter.GetBytes(16);
fileStream.Write(subChunk1, 0, 4);
UInt16 two = 2;
UInt16 one = 1;
Byte[] audioFormat = BitConverter.GetBytes(one);
fileStream.Write(audioFormat, 0, 2);
Byte[] numChannels = BitConverter.GetBytes(channels);
fileStream.Write(numChannels, 0, 2);
Byte[] sampleRate = BitConverter.GetBytes(hz);
fileStream.Write(sampleRate, 0, 4);
Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2); // sampleRate * bytesPerSample*number of channels, here 44100*2*2
fileStream.Write(byteRate, 0, 4);
UInt16 blockAlign = (ushort)(channels * 2);
fileStream.Write(BitConverter.GetBytes(blockAlign), 0, 2);
UInt16 bps = 16;
Byte[] bitsPerSample = BitConverter.GetBytes(bps);
fileStream.Write(bitsPerSample, 0, 2);
Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
fileStream.Write(datastring, 0, 4);
Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
fileStream.Write(subChunk2, 0, 4);
// fileStream.Close();
}
19
Source : stream_c.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
static int stmRandomness( sqlite3_vfs pVfs, int nBuf, byte[] zBuf )
{
int n = 0;
UNUSED_PARAMETER( pVfs );
#if (SQLITE_TEST)
n = nBuf;
Array.Clear( zBuf, 0, n );// memset( zBuf, 0, nBuf );
#else
byte[] sBuf = BitConverter.GetBytes(System.DateTime.Now.Ticks);
zBuf[0] = sBuf[0];
zBuf[1] = sBuf[1];
zBuf[2] = sBuf[2];
zBuf[3] = sBuf[3];
;// memcpy(&zBuf[n], x, sizeof(x))
n += 16;// sizeof(x);
if ( sizeof( DWORD ) <= nBuf - n )
{
//DWORD pid = GetCurrentProcessId();
u32 processId;
#if !SQLITE_SILVERLIGHT
processId = (u32)Process.GetCurrentProcess().Id;
#else
processId = 28376023;
#endif
put32bits( zBuf, n, processId);//(memcpy(&zBuf[n], pid, sizeof(pid));
n += 4;// sizeof(pid);
}
if ( sizeof( DWORD ) <= nBuf - n )
{
//DWORD cnt = GetTickCount();
System.DateTime dt = new System.DateTime();
put32bits( zBuf, n, (u32)dt.Ticks );// memcpy(&zBuf[n], cnt, sizeof(cnt));
n += 4;// cnt.Length;
}
if ( sizeof( long ) <= nBuf - n )
{
long i;
i = System.DateTime.UtcNow.Millisecond;// QueryPerformanceCounter(out i);
put32bits( zBuf, n, (u32)( i & 0xFFFFFFFF ) );//memcpy(&zBuf[n], i, sizeof(i));
put32bits( zBuf, n, (u32)( i >> 32 ) );
n += sizeof( long );
}
#endif
return n;
}
19
Source : GuidCombiPrimaryKeyGeneratorInterceptor.cs
with Apache License 2.0
from crazyants
with Apache License 2.0
from crazyants
public static Guid GenerateComb()
{
byte[] guidArray = Guid.NewGuid().ToByteArray();
DateTime now = DateTime.UtcNow;
// Get the days and milliseconds which will be used to build the byte string
TimeSpan days = new TimeSpan(now.Ticks - BaseDateTicks);
TimeSpan msecs = now.TimeOfDay;
// Convert to a byte array
// Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333
byte[] daysArray = BitConverter.GetBytes(days.Days);
byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));
// Reverse the bytes to match SQL Servers ordering
Array.Reverse(daysArray);
Array.Reverse(msecsArray);
// Copy the bytes into the guid
Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);
return new Guid(guidArray);
}
19
Source : BitConverterNonAllocTests.cs
with MIT License
from crookookoo
with MIT License
from crookookoo
[Test]
public void TestFromInt64() {
Int64 value = (Int64)UnityEngine.Random.Range(float.MinValue, float.MaxValue);
var actual = BitConverter.GetBytes(value);
int offset = 0;
BitConverterNonAlloc.GetBytes(value, _bytes, ref offset);
replacedert.That(offset, Is.EqualTo(actual.Length));
replacedert.That(_bytes.Take(offset), Is.EquivalentTo(actual));
}
19
Source : Guidv2.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
public static Guid NewGuid() {
var guidBytes = Guid.NewGuid().ToByteArray();
var counterBytes = BitConverter.GetBytes(Counter.Increment());
// var counterBytes = BitConverter.GetBytes(Interlocked.Increment(ref _counter));
if (!BitConverter.IsLittleEndian) {
Array.Reverse(counterBytes);
}
guidBytes[08] = counterBytes[1];
guidBytes[09] = counterBytes[0];
guidBytes[10] = counterBytes[7];
guidBytes[11] = counterBytes[6];
guidBytes[12] = counterBytes[5];
guidBytes[13] = counterBytes[4];
guidBytes[14] = counterBytes[3];
guidBytes[15] = counterBytes[2];
return new Guid(guidBytes);
}
19
Source : ByteWriter.cs
with Apache License 2.0
from cs-util-com
with Apache License 2.0
from cs-util-com
public void Write(Int64 value)
{
var pi = BitConverter.GetBytes(value);
_buffer[_pos + 0] = pi[0];
_buffer[_pos + 1] = pi[1];
_buffer[_pos + 2] = pi[2];
_buffer[_pos + 3] = pi[3];
_buffer[_pos + 4] = pi[4];
_buffer[_pos + 5] = pi[5];
_buffer[_pos + 6] = pi[6];
_buffer[_pos + 7] = pi[7];
_pos += 8;
}
19
Source : FrameCounter.cs
with MIT License
from csinkers
with MIT License
from csinkers
public double StartFrame()
{
long currentFrameTicks = _frameTimer.ElapsedTicks;
double deltaSeconds = (currentFrameTicks - _previousFrameTicks) / (double)Stopwatch.Frequency;
_previousFrameTicks = currentFrameTicks;
FrameCount++;
var correlationId = new Guid(_a, _b, _c, BitConverter.GetBytes(FrameCount).Reverse().ToArray());
CoreTrace.SetCorrelationId(correlationId);
CoreTrace.Log.StartFrame(FrameCount, deltaSeconds * 1.0e6);
return deltaSeconds;
}
19
Source : LoggerFactory.cs
with MIT License
from cv-lang
with MIT License
from cv-lang
public LoggerMain GetLogger(string externalId1 = null, string external2 = null, string external3 = null, string external4 = null,
string message = null,
[global::System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
[global::System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[global::System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
var logger= new LoggerMain(LogStorage);
logger.LogElement.UniqueId = Convert.ToBase64String( BitConverter.GetBytes( DateTime.Now.Ticks)).Replace("=","").Replace("/","").Replace("+", "");
logger.LogElement.ExternalId1 = externalId1;
logger.LogElement.ExternalId2 = external2;
logger.LogElement.ExternalId3 = external3;
logger.LogElement.ExternalId4 = external4;
logger.LogElement.Module = module;
logger.LogElement.MemberName = memberName;
logger.Trace($"Start {memberName}");
return logger;
}
19
Source : BufferExtensions.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public static unsafe void ToBytes(this Int64 value, byte[] array, int startIndex)
{
var bytes = BitConverter.GetBytes(value);
for (var i = 0; i < bytes.Length; i++)
{
array[startIndex + i] = bytes[i];
}
/*fixed (byte* ptr = &array[startIndex])
{
*(Int64*)ptr = value;
}*/
}
19
Source : Streams.cs
with MIT License
from d-mod
with MIT License
from d-mod
public static void WriteLong(this Stream stream, long l) {
stream.Write(BitConverter.GetBytes(l));
}
19
Source : CreateCertificates.cs
with MIT License
from damienbod
with MIT License
from damienbod
private X509Certificate2 ChainedConfiguration(BasicConstraints basicConstraints, ValidityPeriod validityPeriod, SubjectAlternativeName subjectAlternativeName, X509Certificate2 signingCertificate, OidCollection enhancedKeyUsages, X509KeyUsageFlags x509KeyUsageFlags, CertificateRequest request)
{
_certificateUtility.AddBasicConstraints(request, basicConstraints);
_certificateUtility.AddExtendedKeyUsages(request, x509KeyUsageFlags);
// set the AuthorityKeyIdentifier. There is no built-in
// support, so it needs to be copied from the Subject Key
// Identifier of the signing certificate and mreplacedaged slightly.
// AuthorityKeyIdentifier is "KeyID=<subject key identifier>"
foreach (var item in signingCertificate.Extensions)
{
if (item.Oid.Value == "2.5.29.14") // "Subject Key Identifier"
{
var issuerSubjectKey = item.RawData;
//var issuerSubjectKey = signingCertificate.Extensions["Subject Key Identifier"].RawData;
var segment = new ArraySegment<byte>(issuerSubjectKey, 2, issuerSubjectKey.Length - 2);
var authorityKeyIdentifier = new byte[segment.Count + 4];
// "KeyID" bytes
authorityKeyIdentifier[0] = 0x30;
authorityKeyIdentifier[1] = 0x16;
authorityKeyIdentifier[2] = 0x80;
authorityKeyIdentifier[3] = 0x14;
segment.CopyTo(authorityKeyIdentifier, 4);
request.CertificateExtensions.Add(new X509Extension("2.5.29.35", authorityKeyIdentifier, false));
break;
}
}
_certificateUtility.AddSubjectAlternativeName(request, subjectAlternativeName);
// Enhanced key usages
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(enhancedKeyUsages, false));
// add this subject key identifier
request.CertificateExtensions.Add(
new X509SubjectKeyIdentifierExtension(request.PublicKey, false));
// certificate expiry: Valid from Yesterday to Now+365 days
// Unless the signing cert's validity is less. It's not possible
// to create a cert with longer validity than the signing cert.
var notbefore = validityPeriod.ValidFrom.AddDays(-1);
if (notbefore < signingCertificate.NotBefore)
{
notbefore = new DateTimeOffset(signingCertificate.NotBefore);
}
var notafter = validityPeriod.ValidTo;
if (notafter > signingCertificate.NotAfter)
{
notafter = new DateTimeOffset(signingCertificate.NotAfter);
}
// cert serial is the epoch/unix timestamp
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var unixTime = Convert.ToInt64((DateTime.UtcNow - epoch).TotalSeconds);
var serial = BitConverter.GetBytes(unixTime);
var cert = request.Create(
signingCertificate,
notbefore,
notafter,
serial);
return cert;
}
19
Source : BlockHeader.cs
with MIT License
from danielgerlag
with MIT License
from danielgerlag
public byte[] CombineHashableElementsWithNonce(long nonce)
{
return MerkelRoot
.Concat(PreviousBlock)
.Concat(BitConverter.GetBytes(Height))
.Concat(BitConverter.GetBytes(Version))
.Concat(BitConverter.GetBytes(nonce))
.ToArray();
}
19
Source : PayloadWriter.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth
public void WriteLong(long value)
{
WriteBytes(BitConverter.GetBytes(value));
}
19
Source : StreamWriteExtensions.cs
with Apache License 2.0
from DataAction
with Apache License 2.0
from DataAction
public static void WriteLong(this Stream stream, long value)
{
stream.Write(BitConverter.GetBytes(value));
}
19
Source : StreamWriteExtensions.cs
with Apache License 2.0
from DataAction
with Apache License 2.0
from DataAction
public static void WriteMoney(this Stream stream, decimal value)
{
var buf = BitConverter.GetBytes(Convert.ToInt64(decimal.Truncate(value * 10000m)));
buf = new[]
{
buf[4], buf[5], buf[6], buf[7],
buf[0], buf[1], buf[2], buf[3]
};
stream.WriteByte(8);
stream.Write(buf, 0, buf.Length);
}
19
Source : BytesUtility.cs
with MIT License
from DataMesh-OpenSource
with MIT License
from DataMesh-OpenSource
public static void WriteLongToBytes(byte[] data, long n, ref int index)
{
byte[] intBytes;
intBytes = BitConverter.GetBytes(n);
Array.Copy(intBytes, 0, data, index, intBytes.Length);
index += intBytes.Length;
}
19
Source : EncodingHelper.cs
with MIT License
from daviddesmet
with MIT License
from daviddesmet
internal static byte[] PreAuthEncode(IReadOnlyList<byte[]> pieces) => BitConverter.GetBytes((long)pieces.Count).Concat(pieces.SelectMany(piece => BitConverter.GetBytes((long)piece.Length).Concat(piece))).ToArray();
19
Source : NetUtility.cs
with GNU General Public License v3.0
from deathkiller
with GNU General Public License v3.0
from deathkiller
public static string ToHexString(long data)
{
return ToHexString(BitConverter.GetBytes(data));
}
19
Source : Helpers.cs
with GNU General Public License v3.0
from DeepHydro
with GNU General Public License v3.0
from DeepHydro
public static double Int64BitsToDouble(long value)
{
return BitConverter.ToDouble(BitConverter.GetBytes(value), 0);
}
19
Source : KrbConstants.cs
with MIT License
from dev-2null
with MIT License
from dev-2null
internal static Guid GetRequestActivityId()
{
var counter = Interlocked.Increment(ref RequestCounter);
var b = BitConverter.GetBytes(counter);
return new Guid(Pid, 0, 0, b[7], b[6], b[5], b[4], b[3], b[2], b[1], b[0]);
}
19
Source : ByteBuffer.cs
with GNU General Public License v2.0
from devmvalvm
with GNU General Public License v2.0
from devmvalvm
public void WriteInt64(Int64 val)
{
if(_length >= _index + 8)
{
byte[] tmp = new byte[8];
tmp = System.BitConverter.GetBytes(val);
_data[_index] = tmp[0];
_data[_index+1] = tmp[1];
_data[_index+2] = tmp[2];
_data[_index+3] = tmp[3];
_data[_index+4] = tmp[4];
_data[_index+5] = tmp[5];
_data[_index+6] = tmp[6];
_data[_index+7] = tmp[7];
_index += 8;
}
#if DEBUG && ERROR
else
{
Globals.l2net_home.Add_Error("write beyond array size WriteInt64");
}
#endif
}
19
Source : converter.cs
with GNU General Public License v2.0
from devmvalvm
with GNU General Public License v2.0
from devmvalvm
public string conv_int64_to_hex(string text)
{
try
{
long temp = System.Convert.ToInt64(text);
byte[] con = System.BitConverter.GetBytes(temp);
string oki = con[0].ToString("X2");
oki += " ";
oki += con[1].ToString("X2");
oki += " ";
oki += con[2].ToString("X2");
oki += " ";
oki += con[3].ToString("X2");
oki += " ";
oki += con[4].ToString("X2");
oki += " ";
oki += con[5].ToString("X2");
oki += " ";
oki += con[6].ToString("X2");
oki += " ";
oki += con[7].ToString("X2");
return oki;
}
catch
{ // ugly but im lazy ...
ulong temp = System.Convert.ToUInt64(text);
byte[] con = System.BitConverter.GetBytes(temp);
string oki = con[0].ToString("X2");
oki += " ";
oki += con[1].ToString("X2");
oki += " ";
oki += con[2].ToString("X2");
oki += " ";
oki += con[3].ToString("X2");
oki += " ";
oki += con[4].ToString("X2");
oki += " ";
oki += con[5].ToString("X2");
oki += " ";
oki += con[6].ToString("X2");
oki += " ";
oki += con[7].ToString("X2");
return oki;
}
}
19
Source : BinaryConverter.cs
with GNU General Public License v3.0
from diegojfer
with GNU General Public License v3.0
from diegojfer
internal static byte[] WriteInt64(Int64 integer, Endianess endianess = Endianess.SystemEndian)
{
byte[] buffer = BitConverter.GetBytes(integer);
if (ShouldReverseBytes(endianess)) {
var span = new Span<byte>(buffer);
span.Reverse();
buffer = span.ToArray();
}
return buffer;
}
19
Source : BambooUtils.cs
with MIT License
from dinhduongha
with MIT License
from dinhduongha
public static Guid NewGuid(DateTime timePart, long randPart)
{
var d = DateTimeOffsetToByteArray(timePart);
var randomPart = BitConverter.GetBytes(randPart);
byte[] bytes = new byte[] { d[3], d[2], d[1], d[0], d[5], d[4], d[7], d[6],
randomPart[0], randomPart[1], randomPart[2], randomPart[3],
randomPart[4], randomPart[5], randomPart[6], randomPart[7]};
return new Guid(bytes);
}
19
Source : BambooUtils.cs
with MIT License
from dinhduongha
with MIT License
from dinhduongha
private static byte[] DateTimeOffsetToByteArray(DateTime value)
{
var micros = (value.Ticks / 10) - UNIXEPOCHMICROSECONDS;
var mc = BitConverter.GetBytes(micros / 1000);
var mx = new[] { mc[7], mc[6], mc[5], mc[4], mc[3], mc[2], mc[1], mc[0] };
var mb = BitConverter.GetBytes(micros / 1000);
var mm = BitConverter.GetBytes(micros % 1000);
var ret = new[] { mb[5], mb[4], mb[3], mb[2], mb[1], mb[0], mm[1], mm[0] }; // Drop byte 6 & 7
return ret;
}
19
Source : UlidSequentialGuidGenerator.cs
with MIT License
from dinhduongha
with MIT License
from dinhduongha
public Guid Create(SequentialGuidType guidType)
{
// We start with 16 bytes of cryptographically strong random data.
var randomBytes = new byte[10];
Rng.Locking(r => r.GetBytes(randomBytes));
// An alternate method: use a normally-created GUID to get our initial
// random data:
// byte[] randomBytes = Guid.NewGuid().ToByteArray();
// This is faster than using RNGCryptoServiceProvider, but I don't
// recommend it because the .NET Framework makes no guarantee of the
// randomness of GUID data, and future versions (or different
// implementations like Mono) might use a different method.
// Now we have the random basis for our GUID. Next, we need to
// create the six-byte block which will be our timestamp.
// We start with the number of milliseconds that have elapsed since
// DateTime.MinValue. This will form the timestamp. There's no use
// being more specific than milliseconds, since DateTime.Now has
// limited resolution.
// Using millisecond resolution for our 48-bit timestamp gives us
// about 5900 years before the timestamp overflows and cycles.
// Hopefully this should be sufficient for most purposes. :)
long timestamp = DateTime.UtcNow.Ticks / 10L - UNIXEPOCHMICROSECONDS;
//long timestamp = DateTime.UtcNow.Ticks / 10000L;
// Then get the bytes
byte[] timestampBytes = BitConverter.GetBytes(timestamp / 1000);
byte[] microsecBytes = BitConverter.GetBytes(timestamp % 1000);
// Since we're converting from an Int64, we have to reverse on
// little-endian systems.
if (BitConverter.IsLittleEndian)
{
Array.Reverse(timestampBytes);
Array.Reverse(microsecBytes);
}
byte[] guidBytes = new byte[16];
switch (guidType)
{
case SequentialGuidType.Sequentialreplacedtring:
case SequentialGuidType.SequentialAsBinary:
// For string and byte-array version, we copy the timestamp first, followed
// by the random data.
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6);
Buffer.BlockCopy(microsecBytes, 6, guidBytes, 6, 2);
Buffer.BlockCopy(randomBytes, 0, guidBytes, 8, 8);
// If formatting as a string, we have to compensate for the fact
// that .NET regards the Data1 and Data2 block as an Int32 and an Int16,
// respectively. That means that it switches the order on little-endian
// systems. So again, we have to reverse.
if (guidType == SequentialGuidType.Sequentialreplacedtring && BitConverter.IsLittleEndian)
{
Array.Reverse(guidBytes, 0, 4);
Array.Reverse(guidBytes, 4, 2);
Array.Reverse(guidBytes, 6, 2);
}
break;
case SequentialGuidType.SequentialAtEnd:
// For sequential-at-the-end versions, we copy the random data first,
// followed by the timestamp.
Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
break;
}
//Console.WriteLine($"Create GUID {new Guid(guidBytes)}");
return new Guid(guidBytes);
}
19
Source : BinaryObjectWriter.cs
with MIT License
from djkaty
with MIT License
from djkaty
public override void Write(long int64) => WriteEndianBytes(BitConverter.GetBytes(int64));
19
Source : DjvuWriter.cs
with MIT License
from DjvuNet
with MIT License
from DjvuNet
public void WriteInt64BigEndian(long value)
{
byte[] buffer = BitConverter.GetBytes(value);
Array.Reverse(buffer);
Write(buffer, 0, 8);
}
19
Source : EsrpDecryptor.cs
with MIT License
from dongle-the-gadget
with MIT License
from dongle-the-gadget
public async Task DecryptBufferToStreamAsync(byte[] buffer, Stream to, int bufferLength, long previousSumBlockLength,
bool isPadded, CancellationToken cancellationToken = default)
{
byte[] offsetBytes = new byte[16];
Array.Copy(BitConverter.GetBytes(previousSumBlockLength), offsetBytes, 8);
using ICryptoTransform ivCrypter = aes.CreateEncryptor(key, new byte[16]);
byte[] newIv = ivCrypter.TransformFinalBlock(offsetBytes, 0, 16);
if (isPadded)
{
aes.Padding = PaddingMode.PKCS7;
}
using ICryptoTransform dec = aes.CreateDecryptor(key, newIv);
using MemoryStream ms = new(buffer, 0, bufferLength);
using CryptoStream cs = new(ms, dec, CryptoStreamMode.Read);
#if NET5_0
await cs.CopyToAsync(to, cancellationToken).ConfigureAwait(false);
#else
await cs.CopyToAsync(to).ConfigureAwait(false);
#endif
}
19
Source : ActiveXMessageFormatter.cs
with MIT License
from dotnetdev-kr
with MIT License
from dotnetdev-kr
public void Write(Message message, object obj)
{
if (message == null)
throw new ArgumentNullException("message");
Stream stream;
int variantType;
if (obj is string)
{
int size = ((string)obj).Length * 2;
if (this.internalBuffer == null || this.internalBuffer.Length < size)
this.internalBuffer = new byte[size];
if (unicodeEncoding == null)
this.unicodeEncoding = new UnicodeEncoding();
this.unicodeEncoding.GetBytes(((string)obj).ToCharArray(), 0, size / 2, this.internalBuffer, 0);
message.properties.SetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY, this.internalBuffer);
message.properties.AdjustSize(NativeMethods.MESSAGE_PROPID_BODY, size);
message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE, size);
message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_TYPE, VT_LPWSTR);
return;
}
else if (obj is byte[])
{
byte[] bytes = (byte[])obj;
if (this.internalBuffer == null || this.internalBuffer.Length < bytes.Length)
this.internalBuffer = new byte[bytes.Length];
Array.Copy(bytes, this.internalBuffer, bytes.Length);
message.properties.SetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY, this.internalBuffer);
message.properties.AdjustSize(NativeMethods.MESSAGE_PROPID_BODY, bytes.Length);
message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE, bytes.Length);
message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_TYPE, VT_UI1 | VT_VECTOR);
return;
}
else if (obj is char[])
{
char[] chars = (char[])obj;
int size = chars.Length * 2;
if (this.internalBuffer == null || this.internalBuffer.Length < size)
this.internalBuffer = new byte[size];
if (unicodeEncoding == null)
this.unicodeEncoding = new UnicodeEncoding();
this.unicodeEncoding.GetBytes(chars, 0, size / 2, this.internalBuffer, 0);
message.properties.SetUI1Vector(NativeMethods.MESSAGE_PROPID_BODY, this.internalBuffer);
message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_SIZE, size);
message.properties.SetUI4(NativeMethods.MESSAGE_PROPID_BODY_TYPE, VT_LPWSTR);
return;
}
else if (obj is byte)
{
stream = new MemoryStream(1);
stream.Write(new byte[] { (byte)obj }, 0, 1);
variantType = VT_UI1;
}
else if (obj is bool)
{
stream = new MemoryStream(1);
if ((bool)obj)
stream.Write(new byte[] { 0xff }, 0, 1);
else
stream.Write(new byte[] { 0x00 }, 0, 1);
variantType = VT_BOOL;
}
else if (obj is char)
{
stream = new MemoryStream(2);
byte[] bytes = BitConverter.GetBytes((Char)obj);
stream.Write(bytes, 0, 2);
variantType = VT_UI2;
}
else if (obj is Decimal)
{
stream = new MemoryStream(8);
byte[] bytes = BitConverter.GetBytes(Decimal.ToOACurrency((Decimal)obj));
stream.Write(bytes, 0, 8);
variantType = VT_CY;
}
else if (obj is DateTime)
{
stream = new MemoryStream(8);
byte[] bytes = BitConverter.GetBytes(((DateTime)obj).Ticks);
stream.Write(bytes, 0, 8);
variantType = VT_DATE;
}
else if (obj is Double)
{
stream = new MemoryStream(8);
byte[] bytes = BitConverter.GetBytes((Double)obj);
stream.Write(bytes, 0, 8);
variantType = VT_R8;
}
else if (obj is Int16)
{
stream = new MemoryStream(2);
byte[] bytes = BitConverter.GetBytes((short)obj);
stream.Write(bytes, 0, 2);
variantType = VT_I2;
}
else if (obj is UInt16)
{
stream = new MemoryStream(2);
byte[] bytes = BitConverter.GetBytes((UInt16)obj);
stream.Write(bytes, 0, 2);
variantType = VT_UI2;
}
else if (obj is Int32)
{
stream = new MemoryStream(4);
byte[] bytes = BitConverter.GetBytes((int)obj);
stream.Write(bytes, 0, 4);
variantType = VT_I4;
}
else if (obj is UInt32)
{
stream = new MemoryStream(4);
byte[] bytes = BitConverter.GetBytes((UInt32)obj);
stream.Write(bytes, 0, 4);
variantType = VT_UI4;
}
else if (obj is Int64)
{
stream = new MemoryStream(8);
byte[] bytes = BitConverter.GetBytes((Int64)obj);
stream.Write(bytes, 0, 8);
variantType = VT_I8;
}
else if (obj is UInt64)
{
stream = new MemoryStream(8);
byte[] bytes = BitConverter.GetBytes((UInt64)obj);
stream.Write(bytes, 0, 8);
variantType = VT_UI8;
}
else if (obj is Single)
{
stream = new MemoryStream(4);
byte[] bytes = BitConverter.GetBytes((float)obj);
stream.Write(bytes, 0, 4);
variantType = VT_R4;
}
else if (obj is IPersistStream)
{
IPersistStream pstream = (IPersistStream)obj;
ComStreamFromDataStream comStream = new ComStreamFromDataStream(new MemoryStream());
NativeMethods.OleSaveToStream(pstream, comStream);
stream = comStream.GetDataStream();
variantType = VT_STREAMED_OBJECT;
}
else if (obj == null)
{
stream = new MemoryStream();
variantType = VT_NULL;
}
else
{
throw new InvalidOperationException(Res.GetString(Res.InvalidTypeSerialization));
}
message.BodyStream = stream;
message.BodyType = variantType;
}
19
Source : RTCP.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
public byte[] GetBytes()
{
byte[] payload = new byte[RTCPREPORT_BYTES_LENGTH];
if (BitConverter.IsLittleEndian)
{
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SyncSource)), 0, payload, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((ulong)SampleStartTime.Ticks)), 0, payload, 4, 8);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((ulong)SampleEndTime.Ticks)), 0, payload, 12, 8);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(StartSequenceNumber)), 0, payload, 20, 2);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(EndSequenceNumber)), 0, payload, 22, 2);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)TotalPackets)), 0, payload, 24, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)OutOfOrder)), 0, payload, 28, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)JitterAverage)), 0, payload, 32, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)JitterMaximum)), 0, payload, 36, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)JitterDiscards)), 0, payload, 40, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)PacketsLost)), 0, payload, 44, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)Duplicates)), 0, payload, 48, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((ulong)BytesReceived)), 0, payload, 52, 8);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)TransmissionRate)), 0, payload, 60, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((ulong)Duration)), 0, payload, 64, 8);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)AverageTransitTime)), 0, payload, 72, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)ReportNumber)), 0, payload, 76, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian((uint)LastReceivedReportNumber)), 0, payload, 80, 4);
}
else
{
Buffer.BlockCopy(BitConverter.GetBytes(SyncSource), 0, payload, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(SampleStartTime.Ticks), 0, payload, 4, 8);
Buffer.BlockCopy(BitConverter.GetBytes(SampleEndTime.Ticks), 0, payload, 12, 8);
Buffer.BlockCopy(BitConverter.GetBytes(StartSequenceNumber), 0, payload, 20, 2);
Buffer.BlockCopy(BitConverter.GetBytes(EndSequenceNumber), 0, payload, 22, 2);
Buffer.BlockCopy(BitConverter.GetBytes(TotalPackets), 0, payload, 24, 4);
Buffer.BlockCopy(BitConverter.GetBytes(OutOfOrder), 0, payload, 28, 4);
Buffer.BlockCopy(BitConverter.GetBytes(JitterAverage), 0, payload, 32, 4);
Buffer.BlockCopy(BitConverter.GetBytes(JitterMaximum), 0, payload, 36, 4);
Buffer.BlockCopy(BitConverter.GetBytes(JitterDiscards), 0, payload, 40, 4);
Buffer.BlockCopy(BitConverter.GetBytes(PacketsLost), 0, payload, 44, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Duplicates), 0, payload, 48, 4);
Buffer.BlockCopy(BitConverter.GetBytes(BytesReceived), 0, payload, 52, 8);
Buffer.BlockCopy(BitConverter.GetBytes(TransmissionRate), 0, payload, 60, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Duration), 0, payload, 64, 8);
Buffer.BlockCopy(BitConverter.GetBytes(AverageTransitTime), 0, payload, 72, 4);
Buffer.BlockCopy(BitConverter.GetBytes(ReportNumber), 0, payload, 76, 4);
Buffer.BlockCopy(BitConverter.GetBytes(LastReceivedReportNumber), 0, payload, 76, 4);
}
return payload;
}
19
Source : ConvertorForRLPEncodingExtensions.cs
with MIT License
from dragonglasscom
with MIT License
from dragonglasscom
public static byte[] ToBytesForRLPEncoding(this long number)
{
return ToBytesFromNumber(BitConverter.GetBytes(number));
}
19
Source : NetworkMessage.cs
with MIT License
from DynaSpan
with MIT License
from DynaSpan
public void Write(long l)
{
byte[] byteArr = System.BitConverter.GetBytes(l);
this.Write(byteArr);
}
19
Source : DateSchema.cs
with Apache License 2.0
from eaba
with Apache License 2.0
from eaba
public override byte[] Encode(DateTime message)
{
long date = message.ConvertToMsTimestamp().LongToBigEndian();
return BitConverter.GetBytes(date);
}
19
Source : TimeSchema.cs
with Apache License 2.0
from eaba
with Apache License 2.0
from eaba
public override byte[] Encode(TimeSpan message)
{
long time = ((long)message.TotalMilliseconds).LongToBigEndian();
return BitConverter.GetBytes(time);
}
19
Source : TimestampSchema.cs
with Apache License 2.0
from eaba
with Apache License 2.0
from eaba
public override byte[] Encode(DateTimeOffset message)
{
long time = message.ToUnixTimeMilliseconds().LongToBigEndian();
return BitConverter.GetBytes(time);
}
19
Source : DeleteProvider.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
public int Delete(IList<int> docs)
{
int count = 0;
lock (this)
{
using (FileStream fs = new FileStream(_DelFileName, FileMode.Append, FileAccess.Write))
{
for (int i = 0; i < docs.Count; i++)
{
int docId = docs[i];
if (!_DeleteTbl.ContainsKey(docId))
{
count++;
_DeleteTbl.Add(docId, 0);
fs.Write(BitConverter.GetBytes((long)docId), 0, sizeof(long));
}
}
}
lock (_DeleteStampLock)
{
_DeleteStamp++;
}
GetDelDocs();
return count;
}
}
19
Source : QueryResultSerialization.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
public static void Write(Stream stream, Type type, object data)
{
if (type == typeof(string))
{
string str = data as string;
byte[] strBuf = Encoding.UTF8.GetBytes(str);
stream.Write(BitConverter.GetBytes(strBuf.Length), 0, sizeof(int));
stream.Write(strBuf, 0, strBuf.Length);
}
else if (type == typeof(bool)) //TinyInt
{
if ((bool)data)
{
stream.WriteByte((byte)1);
}
else
{
stream.WriteByte((byte)0);
}
}
else if (type == typeof(byte)) //TinyInt
{
stream.WriteByte((byte)data);
}
else if (type == typeof(short)) //SmaillInt
{
stream.Write(BitConverter.GetBytes((short)data), 0, sizeof(short));
}
else if (type == typeof(int)) //Int
{
stream.Write(BitConverter.GetBytes((int)data), 0, sizeof(int));
}
else if (type == typeof(long)) //BigInt
{
try
{
stream.Write(BitConverter.GetBytes((long)data), 0, sizeof(long));
}
catch
{
Console.WriteLine();
}
}
else if (type == typeof(DateTime)) //DateTime
{
stream.Write(BitConverter.GetBytes(((DateTime)data).Ticks), 0, sizeof(long));
}
else if (type == typeof(float)) //Float, Real
{
stream.Write(BitConverter.GetBytes((float)data), 0, sizeof(float));
}
else if (type == typeof(double)) //Float
{
stream.Write(BitConverter.GetBytes((double)data), 0, sizeof(double));
}
else if (type == typeof(decimal)) //Float
{
stream.Write(BitConverter.GetBytes((double)((decimal)data)), 0, sizeof(double));
}
else if (type == typeof(byte[])) //Data
{
byte[] databuf = data as byte[];
stream.Write(BitConverter.GetBytes(databuf.Length), 0, sizeof(int));
stream.Write(databuf, 0, databuf.Length);
}
else
{
throw new Exception(string.Format("QueryResultSerialization fail! Unknown data type:{0}",
type.ToString()));
}
}
See More Examples