C # Common extensions for byte arrays are some of the more practical operations we often encounter in programming, so what are the common extensions for C # byte arrays? The following is a list of eight scenarios that are commonly used for illustration.
C # byte array common extension application one: convert to hexadecimal string
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();
}
The second extension returns a hexadecimal string that is attached and, in some cases, is separated by a single space for easy reading and is no longer presented as an example.
C # byte array common extension application two: Convert to Base64 string
public static string ToBase64String(byte[] bytes)
{
return Convert.ToBase64String(bytes);
}
C # byte array common extension application three: Convert to 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);
}
There are many ways to Bitconverter class (ToSingle, ToDouble, ToChar ...). ) that can be extended as above.
C # byte array common extension application four: converting to the specified encoded string
public static string Decode(this byte[] data, Encoding encoding)
{
return encoding.GetString(data);
}
C # byte array common extension application five: 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);
}