-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathConvertExtensions.cs
More file actions
492 lines (454 loc) · 14.4 KB
/
Copy pathConvertExtensions.cs
File metadata and controls
492 lines (454 loc) · 14.4 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
using BytecodeApi.Interop;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
namespace BytecodeApi.Extensions;
/// <summary>
/// Provides <see langword="static" /> methods that extend the <see cref="Convert" /> class.
/// </summary>
public static class ConvertExtensions
{
private const string Base32RFC4648 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
private const string Base32Crockford = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
private static readonly Regex RomanNumberRegex = new("^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$", RegexOptions.IgnoreCase);
extension(Convert)
{
/// <summary>
/// Converts a <see cref="byte" />[] to its equivalent Base32 representation using the RFC4648 charset (ABCDEFGHIJKLMNOPQRSTUVWXYZ234567).
/// </summary>
/// <param name="data">The <see cref="byte" />[] to convert.</param>
/// <returns>
/// An equivalent <see cref="string" /> representation, in Base32, of <paramref name="data" />.
/// </returns>
public static string ToBase32String(byte[] data)
{
return ToBase32String(data, false);
}
/// <summary>
/// Converts a <see cref="byte" />[] to its equivalent Base32 representation.
/// </summary>
/// <param name="data">The <see cref="byte" />[] to convert.</param>
/// <param name="crockford"><see langword="true" /> to use the crockford charset (0123456789ABCDEFGHJKMNPQRSTVWXYZ); <see langword="false" /> to use the RFC4648 charset (ABCDEFGHIJKLMNOPQRSTUVWXYZ234567).</param>
/// <returns>
/// An equivalent <see cref="string" /> representation, in Base32, of <paramref name="data" />.
/// </returns>
public static string ToBase32String(byte[] data, bool crockford)
{
Check.ArgumentNull(data);
if (data.Length == 0)
{
return "";
}
else
{
string charset = crockford ? Base32Crockford : Base32RFC4648;
StringBuilder result = new((data.Length * 8 + 5 - 1) / 5);
int offset = 0;
int last = offset + data.Length;
int buffer = data[offset++];
int bitsLeft = 8;
while (bitsLeft > 0 || offset < last)
{
if (bitsLeft < 5)
{
if (offset < last)
{
buffer <<= 8;
buffer |= data[offset++];
bitsLeft += 8;
}
else
{
int pading = 5 - bitsLeft;
buffer <<= pading;
bitsLeft += pading;
}
}
int index = 31 & (buffer >> bitsLeft - 5);
bitsLeft -= 5;
result.Append(charset[index]);
}
int padding = 8 - result.Length % 8;
if (padding is > 0 and < 8)
{
result.Append('=', padding);
}
return result.ToString();
}
}
/// <summary>
/// Converts an encoded Base32 <see cref="string" /> back to its original <see cref="byte" />[] using the RFC4648 charset (ABCDEFGHIJKLMNOPQRSTUVWXYZ234567).
/// </summary>
/// <param name="str">A <see cref="string" /> representing the Base32 encoded data.</param>
/// <returns>
/// The original <see cref="byte" />[], representing the Base32 <see cref="string" /> in <paramref name="str" />.
/// </returns>
public static byte[] FromBase32String(string str)
{
return FromBase32String(str, false);
}
/// <summary>
/// Converts an encoded Base32 <see cref="string" /> back to its original <see cref="byte" />[].
/// </summary>
/// <param name="str">A <see cref="string" /> representing the Base32 encoded data.</param>
/// <param name="crockford"><see langword="true" /> to use the crockford charset (0123456789ABCDEFGHJKMNPQRSTVWXYZ); <see langword="false" /> to use the RFC4648 charset (ABCDEFGHIJKLMNOPQRSTUVWXYZ234567).</param>
/// <returns>
/// The original <see cref="byte" />[], representing the Base32 <see cref="string" /> in <paramref name="str" />.
/// </returns>
public static byte[] FromBase32String(string str, bool crockford)
{
Check.ArgumentNull(str);
str = str.Trim().TrimEnd('=').ToUpper();
if (str.Length == 0)
{
return Array.Empty<byte>();
}
else
{
string charset = crockford ? Base32Crockford : Base32RFC4648;
byte[] result = new byte[str.Length * 5 / 8];
int buffer = 0;
int index = 0;
int bitsLeft = 0;
foreach (char c in str)
{
int charValue = -1;
for (int i = 0; i < 32; i++)
{
if (charset[i] == c)
{
charValue = i;
break;
}
}
if (charValue == -1)
{
Throw.Argument(nameof(str), "Illegal character in Base32 string.");
}
buffer <<= 5;
buffer |= charValue & 31;
bitsLeft += 5;
if (bitsLeft >= 8)
{
result[index++] = (byte)(buffer >> (bitsLeft - 8));
bitsLeft -= 8;
}
}
return result;
}
}
/// <summary>
/// Converts a zero-based Excel column index to a string (like A, B, ... AA, AB, ...).
/// </summary>
/// <param name="index">A <see cref="int" /> representing an Excel column index.</param>
/// <returns>
/// A <see cref="string" /> value with the Excel column string, converted from the zero-based column index.
/// </returns>
public static string ToExcelColumnString(int index)
{
return ToExcelColumnString(index, false);
}
/// <summary>
/// Converts a zero-based or one-based Excel column index to a string (like A, B, ... AA, AB, ...).
/// </summary>
/// <param name="index">A <see cref="int" /> representing an Excel column index.</param>
/// <param name="oneBased"><see langword="true" /> to treat <paramref name="index" /> as a one-based index; otherwise, <see langword="false" />.</param>
/// <returns>
/// A <see cref="string" /> value with the Excel column string, converted from the zero-based or one-based column index.
/// </returns>
public static string ToExcelColumnString(int index, bool oneBased)
{
if (oneBased) Check.ArgumentOutOfRangeEx.Greater0(index);
else Check.ArgumentOutOfRangeEx.GreaterEqual0(index);
if (oneBased)
{
index--;
}
string str = "";
while (index >= 0)
{
str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index % 26] + str;
index = index / 26 - 1;
}
return str;
}
/// <summary>
/// Converts an Excel column name (like A, B, ... AA, AB, ...) to a zero-based index.
/// </summary>
/// <param name="str">A <see cref="string" /> representing an Excel column name.</param>
/// <returns>
/// A <see cref="int" /> value with the zero-based index, converted from the Excel column name.
/// </returns>
public static int FromExcelColumnString(string str)
{
return FromExcelColumnString(str, false);
}
/// <summary>
/// Converts an Excel column name (like A, B, ... AA, AB, ...) to a zero-based or one-based index.
/// </summary>
/// <param name="str">A <see cref="string" /> representing an Excel column name.</param>
/// <param name="oneBased"><see langword="true" /> to return a one-based index; otherwise, <see langword="false" />.</param>
/// <returns>
/// A <see cref="int" /> value with the zero-based or one-based index, converted from the Excel column name.
/// </returns>
public static int FromExcelColumnString(string str, bool oneBased)
{
Check.ArgumentNull(str);
int sum = 0;
foreach (char columnChar in str.ToUpper())
{
if (columnChar is < 'A' or > 'Z') throw Throw.Argument(nameof(str), "String must contain only letters from A-Z.");
sum *= 26;
sum += columnChar - 'A' + 1;
}
if (!oneBased)
{
sum--;
}
return sum;
}
/// <summary>
/// Converts an integer to a roman numeral. If <paramref name="value" /> is not between 1 and 3999, an exception is thrown.
/// <para>Examples: I, II, III, IV, V, VI, VII, VIII, IX, X</para>
/// </summary>
/// <param name="value">A <see cref="int" /> value to convert to a roman numeral.</param>
/// <returns>
/// A roman number <see cref="string" /> that was converted from the specified integer.
/// </returns>
public static string ToRomanNumber(int value)
{
Check.ArgumentOutOfRange(value is >= 1 and <= 3999, nameof(value), "Number must be in range of 1...3999.");
// 1 I
// 5 V
// 10 X
// 50 L
// 100 C
// 500 D
// 1000 M
string result = "";
while (value > 0)
{
if (value >= 1000)
{
result += "M";
value -= 1000;
}
else if (value >= 900)
{
result += "CM";
value -= 900;
}
else if (value >= 500)
{
result += "D";
value -= 500;
}
else if (value >= 400)
{
result += "CD";
value -= 400;
}
else if (value >= 100)
{
result += "C";
value -= 100;
}
else if (value >= 90)
{
result += "XC";
value -= 90;
}
else if (value >= 50)
{
result += "L";
value -= 50;
}
else if (value >= 40)
{
result += "XL";
value -= 40;
}
else if (value >= 10)
{
result += "X";
value -= 10;
}
else if (value >= 9)
{
result += "IX";
value -= 9;
}
else if (value >= 5)
{
result += "V";
value -= 5;
}
else if (value >= 4)
{
result += "IV";
value -= 4;
}
else if (value >= 1)
{
result += "I";
value--;
}
}
return result;
}
/// <summary>
/// Converts a roman number <see cref="string" /> to an integer.
/// <para>Examples: I, II, III, IV, V, VI, VII, VIII, IX, X</para>
/// </summary>
/// <param name="value">A roman number <see cref="string" />.</param>
/// <returns>
/// A <see cref="int" /> value that was converted from the roman number <see cref="string" />.
/// </returns>
public static int FromRomanNumber(string value)
{
Check.ArgumentNull(value);
Check.ArgumentEx.StringNotEmpty(value);
Check.Format(RomanNumberRegex.IsMatch(value), "String is not a valid roman number.");
// 1 I
// 5 V
// 10 X
// 50 L
// 100 C
// 500 D
// 1000 M
int result = 0;
value = value.ToUpper();
while (value.Length > 0)
{
if (value.StartsWith('M'))
{
result += 1000;
value = value[1..];
}
else if (value.StartsWith("CM"))
{
result += 900;
value = value[2..];
}
else if (value.StartsWith('D'))
{
result += 500;
value = value[1..];
}
else if (value.StartsWith("CD"))
{
result += 400;
value = value[2..];
}
else if (value.StartsWith('C'))
{
result += 100;
value = value[1..];
}
else if (value.StartsWith("XC"))
{
result += 90;
value = value[2..];
}
else if (value.StartsWith('L'))
{
result += 50;
value = value[1..];
}
else if (value.StartsWith("XL"))
{
result += 40;
value = value[2..];
}
else if (value.StartsWith('X'))
{
result += 10;
value = value[1..];
}
else if (value.StartsWith("IX"))
{
result += 9;
value = value[2..];
}
else if (value.StartsWith('V'))
{
result += 5;
value = value[1..];
}
else if (value.StartsWith("IV"))
{
result += 4;
value = value[2..];
}
else if (value.StartsWith('I'))
{
result++;
value = value[1..];
}
else
{
throw Throw.Argument(nameof(value), "String is not a valid roman number.");
}
}
return result;
}
/// <summary>
/// Converts the specified <see cref="byte" />[] to a structure of type <typeparamref name="T" />.
/// </summary>
/// <typeparam name="T">The type of the structure to return.</typeparam>
/// <param name="array">A <see cref="byte" />[] with the binary representation of the structure. This array must have an equivalent size of <see cref="Marshal" />.SizeOf(<see langword="typeof" />(<typeparamref name="T" />)).</param>
/// <returns>
/// The structure of type <typeparamref name="T" /> this method creates.
/// </returns>
public static T ToStructure<T>(byte[] array) where T : struct
{
Check.ArgumentNull(array);
Check.Argument(array.Length == Marshal.SizeOf<T>(), nameof(array), "Array size must be equivalent to the size of the structure type.");
using HGlobal hglobal = HGlobal.FromArray(array);
return hglobal.ToStructure<T>();
}
/// <summary>
/// Converts the specified structure of type <typeparamref name="T" /> to a <see cref="byte" />[] with the size of <see cref="Marshal" />.SizeOf(<see langword="typeof" />(<typeparamref name="T" />)).
/// </summary>
/// <typeparam name="T">The type of the structure to convert.</typeparam>
/// <param name="structure">The structure to convert to a <see cref="byte" />[].</param>
/// <returns>
/// An equivalent <see cref="byte" />[] representation of <paramref name="structure" /> with the size of <see cref="Marshal" />.SizeOf(<see langword="typeof" />(<typeparamref name="T" />)).
/// </returns>
public static byte[] FromStructure<T>(T structure) where T : struct
{
using HGlobal hglobal = HGlobal.FromStructure(structure);
return hglobal.ToArray();
}
/// <summary>
/// Converts a <see cref="byte" />[] to an <see cref="Bitmap" />. The <paramref name="array" /> object should represent the binary of a valid image file.
/// </summary>
/// <param name="array">A <see cref="byte" />[] that represents a valid image file.</param>
/// <returns>
/// A new <see cref="Bitmap" /> object, created from the contents of <paramref name="array" />.
/// </returns>
[SupportedOSPlatform("windows")]
public static Bitmap ToBitmap(byte[] array)
{
Check.ArgumentNull(array);
using MemoryStream memoryStream = new(array);
return new(memoryStream);
}
/// <summary>
/// Converts a <see cref="byte" />[] to an <see cref="Icon" />. The <paramref name="array" /> object should represent the binary of a valid icon file.
/// </summary>
/// <param name="array">A <see cref="byte" />[] that represents a valid icon file.</param>
/// <returns>
/// A new <see cref="Icon" /> object, created from the contents of <paramref name="array" />.
/// </returns>
[SupportedOSPlatform("windows")]
public static Icon ToIcon(byte[] array)
{
Check.ArgumentNull(array);
using MemoryStream memoryStream = new(array);
return new(memoryStream);
}
}
}