您的位置:首页 > 其它

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

2013-01-27 11:58 561 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐