-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
ByteUtils.cs
76 lines (60 loc) · 1.93 KB
/
ByteUtils.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Globalization;
using System.Text;
namespace Test.Cryptography
{
internal static class ByteUtils
{
internal static byte[] AsciiBytes(string s)
{
byte[] bytes = new byte[s.Length];
for (int i = 0; i < s.Length; i++)
{
bytes[i] = (byte)s[i];
}
return bytes;
}
internal static byte[] HexToByteArray(this string hexString)
{
byte[] bytes = new byte[hexString.Length / 2];
for (int i = 0; i < hexString.Length; i += 2)
{
string s = hexString.Substring(i, 2);
bytes[i / 2] = byte.Parse(s, NumberStyles.HexNumber, null);
}
return bytes;
}
internal static string ByteArrayToHex(this byte[] bytes)
{
return ByteArrayToHex((ReadOnlySpan<byte>)bytes);
}
internal static string ByteArrayToHex(this Span<byte> bytes)
{
return ByteArrayToHex((ReadOnlySpan<byte>)bytes);
}
internal static string ByteArrayToHex(this ReadOnlyMemory<byte> bytes)
{
return ByteArrayToHex(bytes.Span);
}
internal static string ByteArrayToHex(this ReadOnlySpan<byte> bytes)
{
StringBuilder builder = new StringBuilder(bytes.Length * 2);
for (int i = 0; i < bytes.Length; i++)
{
builder.Append($"{bytes[i]:X2}");
}
return builder.ToString();
}
internal static byte[] RepeatByte(byte b, int count)
{
byte[] value = new byte[count];
for (int i = 0; i < count; i++)
{
value[i] = b;
}
return value;
}
}
}