35 lines
1.3 KiB
C#
35 lines
1.3 KiB
C#
|
using System;
|
|||
|
using System.Linq;
|
|||
|
|
|||
|
namespace Swan {
|
|||
|
/// <summary>
|
|||
|
/// Provides various extension methods for byte arrays and streams.
|
|||
|
/// </summary>
|
|||
|
public static class ByteArrayExtensions {
|
|||
|
/// <summary>
|
|||
|
/// Converts an array of bytes to a base-64 encoded string.
|
|||
|
/// </summary>
|
|||
|
/// <param name="bytes">The bytes.</param>
|
|||
|
/// <returns>A <see cref="String" /> converted from an array of bytes.</returns>
|
|||
|
public static String ToBase64(this Byte[] bytes) => Convert.ToBase64String(bytes);
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// Converts a set of hexadecimal characters (uppercase or lowercase)
|
|||
|
/// to a byte array. String length must be a multiple of 2 and
|
|||
|
/// any prefix (such as 0x) has to be avoided for this to work properly.
|
|||
|
/// </summary>
|
|||
|
/// <param name="this">The hexadecimal.</param>
|
|||
|
/// <returns>
|
|||
|
/// A byte array containing the results of encoding the specified set of characters.
|
|||
|
/// </returns>
|
|||
|
/// <exception cref="ArgumentNullException">hex.</exception>
|
|||
|
public static Byte[] ConvertHexadecimalToBytes(this String @this) {
|
|||
|
if(String.IsNullOrWhiteSpace(@this)) {
|
|||
|
throw new ArgumentNullException(nameof(@this));
|
|||
|
}
|
|||
|
|
|||
|
return Enumerable.Range(0, @this.Length / 2).Select(x => Convert.ToByte(@this.Substring(x * 2, 2), 16)).ToArray();
|
|||
|
}
|
|||
|
}
|
|||
|
}
|