合并字节数组
public static byte[] CombineByteArray(byte[][] byteArra)
{
System.IO.MemoryStream aMS = new System.IO.MemoryStream();
byte[] tempBA ;
for (int i = 0; i < byteArra.Length; i++)
{
tempBA = byteArra[i];
aMS.Write(tempBA, 0, tempBA.Length);
}
return aMS.ToArray();
}
//字节数组截取 32位
public unsafe static byte[] SubByteArray(byte[] src, int begin, int length)
{
if (src.Length < begin + length)
throw new Exception("源数组长度不够。");
byte[] rT = new byte[length];
int len = length;
fixed (byte* pSrc = src, pRt = rT)
{
byte *p = pSrc + begin;
int* i1 = (int*)p;
int* i2 = (int*)pRt;
while (len >= 4)
{
*i2++ = *i1++;
len -= 4;
}
byte* c1 = (byte*)i1;
byte* c2 = (byte*)i2;
while (len > 0)
{
*c2++ = *c1++;
len--;
}
}
return rT;
}
// from http://www.pinvoke.net/default.aspx/msvcrt/memcmp.html
C# Signature (x86 and x64):
[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern int memcmp(byte[] b1, byte[] b2, UIntPtr count);
C# Signature (x64 only):
[DllImport("msvcrt.dll")]
static extern int memcmp(IntPtr ptr1, IntPtr ptr2, int count);
C# Unsafe Signature (x64 only):
[DllImport("msvcrt.dll")]
static extern unsafe int memcmp(void* ptr1, void* ptr2, int count);
//Extension Method example
public static class ByteArrayExtensions
{
[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int memcmp(byte[] b1, byte[] b2, UIntPtr count);
public static bool SequenceEqual(this byte[] b1, byte[] b2)
{
if (b1 == b2) return true; //reference equality check
if (b1 == null || b2 == null || b1.Length != b2.Length) return false;
return memcmp(b1, b2, new UIntPtr((uint)b1.Length)) == 0;
}
}
//http://www.cplusplus.com/reference/clibrary/cstring/memcmp/
unsafe bool CompareByteArray(byte[] b1, byte[] b2)
{
fixed (byte* p1 = b1)
fixed (byte* p2 = b2)
{
return memcmp((void*)p1, (void*)p2, b1.Length) == 0;
}
}