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

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;
}

 

 

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值