-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathBitString.cs
More file actions
98 lines (85 loc) · 2.46 KB
/
BitString.cs
File metadata and controls
98 lines (85 loc) · 2.46 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Text;
namespace ReClassNET.Util
{
public static class BitString
{
/// <summary>
/// Converts the value to the corresponding bit string.
/// Format: 0000 0000
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The corresponding bit string.</returns>
public static string ToString(byte value)
{
return AddPaddingAndBuildBlocks(8, Convert.ToString(value, 2));
}
/// <summary>
/// Converts the value to the corresponding bit string.
/// Format: 0000 0000 0000 0000
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The corresponding bit string.</returns>
public static string ToString(short value)
{
return AddPaddingAndBuildBlocks(16, Convert.ToString(value, 2));
}
/// <summary>
/// Converts the value to the corresponding bit string.
/// Format: 0000 0000 0000 0000 0000 0000 0000 0000
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The corresponding bit string.</returns>
public static string ToString(int value)
{
return AddPaddingAndBuildBlocks(32, Convert.ToString(value, 2));
}
/// <summary>
/// Converts the value to the corresponding bit string.
/// Format: 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The corresponding bit string.</returns>
public static string ToString(long value)
{
return AddPaddingAndBuildBlocks(64, Convert.ToString(value, 2));
}
private static string AddPaddingAndBuildBlocks(int bits, string value)
{
const int BitsPerBlock = 4;
var sb = new StringBuilder(bits);
var padding = bits - value.Length;
// Add full padding blocks.
while (padding > BitsPerBlock)
{
sb.Append("0000 ");
padding -= BitsPerBlock;
}
// Add only a part of a block.
if (padding > 0)
{
// {padding} 0 bits
for (var i = 0; i < padding; ++i)
{
sb.Append('0');
}
// and {4 - padding} bits of the value.
sb.Append(value, 0, BitsPerBlock - padding);
if (value.Length > padding)
{
sb.Append(' ');
}
}
// Add all remaining blocks.
for (var i = padding == 0 ? 0 : BitsPerBlock - padding; i < value.Length; i += BitsPerBlock)
{
sb.Append(value, i, BitsPerBlock);
if (i < value.Length - BitsPerBlock)
{
sb.Append(' ');
}
}
return sb.ToString();
}
}
}