Stream、byte配列と16進文字列の相互変換

6330 ワード

Streamをbyte配列に変換するには、次の手順に従います.
/// <summary> 
///   Stream   byte[] 
/// </summary> 
public static byte[] StreamToBytes(Stream stream)
{
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);

    //   
    stream.Seek(0, SeekOrigin.Begin);
    return bytes;
}

byte配列はStreamに変換されます.
/// <summary> 
///   byte[]   Stream 
/// </summary> 
public static Stream BytesToStream(byte[] bytes)
{
    Stream stream = new MemoryStream(bytes);
    return stream;
} 

byte配列は16進文字列に変換されます.
/// <summary>
///  
/// </summary>
/// <param name="bytes"> </param>
/// <returns></returns>
private static string ByteArrayToHexStr(byte[] byteArray)
{
    int capacity = byteArray.Length * 2;
    StringBuilder sb = new StringBuilder(capacity);

    if (byteArray != null)
    {
        for (int i = 0; i < byteArray.Length; i++)
        {
            sb.Append(byteArray[i].ToString("X2"));
        }
    }
    return sb.ToString();
} 

16進文字列をbyte配列に変換するには、次の手順に従います.
/// <summary>
///   
/// </summary>
/// <param name="hexString"> </param>
/// <returns></returns>
private static byte[] HexStrToByteArray(string hexString)
{
    hexString = hexString.Replace(" ", "");
    if ((hexString.Length % 2) != 0)
        throw new ArgumentException(" ");
    byte[] buffer = new byte[hexString.Length / 2];
    for (int i = 0; i < buffer.Length; i++)
    {
        buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 0x10);
    }
    return buffer;
}