C# byte数组常用扩展浅析
2010-08-31 17:39
281 查看
byte数组常用扩展以及实现实例。
C# byte数组常用扩展是我们编程中经常会碰到的一些实用性很强的操作,那么C# byte数组常用扩展都有哪些呢?下面将列出并用实例演示常用八种情况。
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); }
C# byte数组常用扩展的八种情况就向你介绍到这里,希望对你了解和学习C# byte数组常用扩展有所帮助
相关文章推荐
- C# byte数组常用扩展浅析
- C# byte数组常用扩展 八种情况
- c# 扩展方法奇思妙用基础篇三:byte 常用扩展
- c# 扩展方法奇思妙用基础篇三:byte 常用扩展
- c#扩展方法奇思妙用基础篇三:byte 常用扩展
- C# byte数组常用扩展浅析(转)
- C# 图片与字节数组(byte[])二进制相互转换,获取大小像素扩展名
- c#扩展方法奇思妙用基础篇三:byte 常用扩展
- c#中如何将byte数组转换成string从而在textbox中显示出来?
- C# 将文件转化成byte[]数组
- C# 二进制替换第二弹 二进制替换深入研究---List 与byte[] 效率对比 byte[] 数组 替换
- C# 保存 byte 数组 到文件中, 用vs2005 打开该文件查看
- C# string byte数组转换解析
- java c#指定长度 中int与byte数组互转代码详细分析
- JS中数组的常用方法(包含es6扩展)
- C# 将文件转化成byte[]数组
- c# 多线程里面创建byte数组发生内存溢出异常求解
- C# 对象、文件与二进制串(byte数组)之间的转换
- C# string byte数组转换解析
- C# 一些常用的字符串扩展方法