温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#下byte数组常用扩展浅析

发布时间:2021-09-17 16:28:55 来源:亿速云 阅读:146 作者:chen 栏目:编程语言

本篇内容介绍了“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 < 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数组常用扩展浅析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI