C# byte数组常用扩展(转载)

[size=medium]C# byte数组常用扩展(转载)[/size]

C# byte数组常用扩展应用一:转换为十六进制字符串

public static string ToHex(this byte b)
{
return b.ToString("X2");
}

public static string ToHex(this IEnumerable<byte> bytes)
{
var sb = new StringBuilder();
foreach (byte b in bytes)
sb.Append(b.ToString("X2"));
return sb.ToString();
}
第二个扩展返回的十六进制字符串是连着的,一些情况下为了阅读方便会用一个空格分开,处理比较简单,不再给出示例。

C# byte数组常用扩展应用二:转换为Base64字符串

public static string ToBase64String(byte[] bytes)
{
return Convert.ToBase64String(bytes);
}
C# byte数组常用扩展应用三:转换为基础数据类型

public static int ToInt(this byte[] value, int startIndex)
{
return BitConverter.ToInt32(value, startIndex);
}
public static long ToInt64(this byte[] value, int startIndex)
{
return BitConverter.ToInt64(value, startIndex);
}
BitConverter类还有很多方法(ToSingle、ToDouble、ToChar...),可以如上进行扩展。

C# byte数组常用扩展应用四:转换为指定编码的字符串

public static string Decode(this byte[] data, Encoding encoding)
{
return encoding.GetString(data);
}
C# byte数组常用扩展应用五:Hash

//使用指定算法Hash
public static byte[] Hash(this byte[] data, string hashName)
{
HashAlgorithm algorithm;
if (string.IsNullOrEmpty(hashName)) algorithm = HashAlgorithm.Create();
else algorithm = HashAlgorithm.Create(hashName);
return algorithm.ComputeHash(data);
}
//使用默认算法Hash
public static byte[] Hash(this byte[] data)
{
return Hash(data, null);
}
C# byte数组常用扩展应用六:位运算

//index从0开始
//获取取第index是否为1
public static bool GetBit(this byte b, int index)
{
return (b & (1 << index)) > 0;
}
//将第index位设为1
public static byte SetBit(this byte b, int index)
{
b |= (byte)(1 << index);
return b;
}
//将第index位设为0
public static byte ClearBit(this byte b, int index)
{
b &= (byte)((1 << 8) - 1 - (1 << index));
return b;
}
//将第index位取反
public static byte ReverseBit(this byte b, int index)
{
b ^= (byte)(1 << index);
return b;
}
C# byte数组常用扩展应用七:保存为文件

public static void Save(this byte[] data, string path)
{
File.WriteAllBytes(path, data);
}
C# byte数组常用扩展应用八:转换为内存流

public static MemoryStream ToMemoryStream(this byte[] data)
{
return new MemoryStream(data);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值