Stream、byte数组与16进制字符串的相互转换

Stream转换为byte数组:

///  
/// 将 Stream 转成 byte[] 
///  
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:

///  
/// 将 byte[] 转成 Stream 
///  
public static Stream BytesToStream(byte[] bytes)
{
    Stream stream = new MemoryStream(bytes);
    return stream;
} 

 byte数组转换为16进制字符串:

/// 
/// 字节数组转换成十六进制字符串
/// 
/// 要转换的字节数组
/// 
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数组:

/// 
/// 十六进制字符串转换成字节数组 
/// 
/// 要转换的字符串
/// 
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;
}

 

 

转载于:https://www.cnblogs.com/yayadoudou/archive/2013/01/27/2878588.html

你可能感兴趣的:(Stream、byte数组与16进制字符串的相互转换)