-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathExtensions.ByteArray.cs
50 lines (42 loc) · 1.45 KB
/
Extensions.ByteArray.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Diagnostics.Contracts;
using System.Text;
namespace Open.Collections;
public static partial class Extensions
{
/// <summary>
/// Converts a string to a <see cref="byte"/> array.
/// </summary>
/// <param name="value">The string value.</param>
/// <param name="encoding">Default is UTF8.</param>
public static byte[] ToByteArray(this string value, Encoding? encoding = null)
{
if (value is null) throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
return (encoding ?? Encoding.UTF8).GetBytes(value);
}
/// <summary>
/// Converts a string to a <see cref="sbyte"/> array.
/// </summary>
/// <param name="value">The string value.</param>
/// <param name="encoding">Default is UTF8.</param>
public static sbyte[] ToSbyteArray(this string value, Encoding? encoding = null)
{
if (value is null) throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
return value.ToByteArray(encoding).ToSbyteArray();
}
/// <summary>
/// Directly converts a <see cref="byte"/> array (byte-by-byte) to an <see cref="sbyte"/> array.
/// </summary>
/// <param name="bytes">The bytes.</param>
public static sbyte[] ToSbyteArray(this byte[] bytes)
{
if (bytes is null) throw new ArgumentNullException(nameof(bytes));
Contract.EndContractBlock();
sbyte[]? sbytes = new sbyte[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
sbytes[i] = (sbyte)bytes[i];
return sbytes;
}
}