首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 位元組陣列截取函數 SubByte 實作

     編輯:關於C#

SubByte 函數實作

/// 
/// 截取位元組陣列
/// 
/// 來源陣列
/// 起始索引
/// 截取長度
/// 截取後的新陣列
public byte[] SubByte(byte[] srcBytes, int startIndex, int length) {
  System.IO.MemoryStream bufferStream = new System.IO.MemoryStream();
  byte[] returnByte = new byte[] { };
  if (srcBytes == null) return returnByte;
  if (startIndex < 0) startIndex = 0;
  if (startIndex < srcBytes.Length) {
    if (length < 1 || length > srcBytes.Length - startIndex)
      length = srcBytes.Length - startIndex;
    bufferStream.Write(srcBytes, startIndex, length);
    returnByte = bufferStream.ToArray();
    bufferStream.SetLength(0);
    bufferStream.Position = 0;
  }
  bufferStream.Close();
  bufferStream.Dispose();
  return returnByte;
}

使用 MemoryStream 寫入指定範圍並轉為陣列回傳,含參數驗證與資源釋放。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved