It happens everyday
หลังจากที่มีปัญหากับการทำงาน เพราะว่าไม่รู้ว่าจะเอา byte array สองตัวมาต่อกันยังไง ตอนนี้ผมได้คำตอบแล้ว เอามาเขียนไว้หน่อย เผื่อจะได้ใช้ในอนาคต
ให้ a1, a2, a3 เป็น byte array ที่เราอยากจะเอามาต่อกัน แล้ว rv เป็น byte array ที่ได้จากการเอามาต่อกัน
เขียนได้ว่า
byte[] rv = new byte[ a1.Length + a2.Length + a3.Length ];
System.Buffer.BlockCopy( a1, 0, rv, 0, a1.Length );
System.Buffer.BlockCopy( a2, 0, rv, a1.Length, a2.Length );
System.Buffer.BlockCopy( a3, 0, rv, a1.Length + a2.Length, a3.Length );
ง่ายๆ แค่นี้เอง..
เอามาทำเป็น Function กันดีกว่า
public static byte[] Combine(byte[] first, byte[] second)
{
byte[] ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}
public static byte[] Combine(byte[] first, byte[] second, byte[] third)
{
byte[] ret = new byte[first.Length + second.Length + third.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
third.Length);
return ret;
}
public static byte[] Combine(params byte[][] arrays)
{
byte[] ret = new byte[arrays.Sum(x => x.Length)];
int offset = 0;
foreach (byte[] data in arrays)
{
Buffer.BlockCopy(data, 0, ret, offset, data.Length);
offset += data.Length;
}
return ret;
}
Internet คือความรู้ และเป็นคำตอบสำหรับทุกๆ สิ่ง
ที่มา: http://stackoverflow.com/questions/415291/best-way-to-combine-2-or-more-byte-arrays-in-c
การใช้ชีวิตอยู่ในทุกๆ วัน
มัักมีเรื่องราวต่างๆ
เกิดขึ้นได้เสมอ..
มีทั้งความสุข
ความทุกข์
หลายอย่างเลือนหายไป
จากความทรงจำ..
เพื่อเก็บบันทึกคุณค่าของเรื่องราวเหล่านั้น
Blog นี้จึงได้เกิดขึ้นมา
..เอ็กซ์
Leave a reply