-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXConvert.cs
More file actions
102 lines (90 loc) · 3.1 KB
/
XConvert.cs
File metadata and controls
102 lines (90 loc) · 3.1 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
/* Attributions
* Mike DePaul
* https://github.com/mdepaul/XConvert.git
* **/
using System;
using System.Collections.Generic;
using System.Text;
namespace MD.XConvert
{
/// <summary>
/// Conversion utilities as extention methods
/// </summary>
public static class XConvert
{
public static int ToInt32(this byte byteValue)
{
return Convert.ToInt32(byteValue);
}
public static string ToBase64String(this byte[] bytes)
{
return Convert.ToBase64String(bytes);
}
public static byte[] FromBase64String(this string input)
{
return Convert.FromBase64String(input);
}
public static string ToSafeBase64String(this byte[] bytes)
{
return ToBase64String(bytes).Replace("/", ".").Replace("+", "_").Replace("==", "--");
}
public static byte[] FromSafeBase64String(this string input)
{
return Convert.FromBase64String(input.Replace(".", "/").Replace("_", "+").Replace("--", "=="));
}
public static string ToHex(this byte[] bytes)
{
StringBuilder hex = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
hex.AppendFormat("{0:x2}", b);
return hex.ToString().ToUpper();
}
public static byte[] FromHex(this string hex)
{
int numberChars = hex.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
public static string Sort(this string value)
{
StringBuilder sb = new StringBuilder(value.Length);
SortedSet<char> set = GetSortedSet(value);
foreach (var item in set)
{
sb.Append(item);
}
return sb.ToString();
}
public static string Reverse(this string value)
{
StringBuilder sb = new StringBuilder("".PadRight(value.Length, ' '), value.Length);
int pos = value.Length - 1;
foreach (var theCharacter in value.ToCharArray())
{
sb[pos] = theCharacter;
pos--;
}
return sb.ToString();
}
private static SortedSet<char> GetSortedSet(string value)
{
SortedSet<char> sortedSet = new SortedSet<char>();
foreach (var theCharacter in value.ToCharArray())
{
sortedSet.Add(theCharacter);
}
return sortedSet;
}
/// <summary>
/// Encodes all the characters in the specified string into a sequence of bytes.
/// </summary>
/// <param name="value">The string </param>
/// <returns></returns>
public static byte[] GetBytes(this string value)
{
return Encoding.UTF8.GetBytes(value);
}
}
}