Simple analysis of common extensions of C # byte arrays

Source: Internet
Author: User

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);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.