Analysis on the Common extension of byte Array under C #
This article introduces the relevant knowledge of "analysis of common extensions of byte arrays under C#". In the actual operation process of cases, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!
C#byte array common extension application 1: conversion to hexadecimal string
public static string ToHex(this byte b) { return b.ToString("X2"); } public static string ToHex(this IEnumerable bytes) { var sb = new StringBuilder(); foreach (byte b in bytes) sb.Append(b.ToString("X2")); return sb.ToString(); }
The hexadecimal string returned by the second extension is contiguous. In some cases, it will be separated by a space for reading convenience. The processing is relatively simple, and no more examples are given.
C#byte array common extension application 2: conversion to Base64 string
public static string ToBase64String(byte[] bytes) { return Convert.ToBase64String(bytes); }
C#byte array common extension application three: conversion to the underlying data type
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 class also has many methods (ToSingle, ToDouble, ToChar...), It can be extended as above.
C#byte array commonly used extension application four: conversion to the specified encoded string
public static string Decode(this byte[] data, Encoding encoding) { return encoding.GetString(data); }
C#byte array commonly used extension application five: Hash
//Hash (this byte[] data, string hashName) { HashAlgorithm algorithm; if (string.IsNullOrEmpty(hashName)) algorithm = HashAlgorithm.Create(); else algorithm = HashAlgorithm.Create(hashName); return algorithm.ComputeHash(data); } //Use default hash algorithm public static byte[] Hash(this byte[] data) { return Hash(data, null); }
C#byte array commonly used extensions apply six: bit operations
//index starts from 0//get if index is 1 public static bool GetBit(this byte b, int index) { return (b & (1 < 0;)} //set index bit to 1 public static byte SetBit(this byte b, int index) { b| = (byte)(1