Skip to content

Commit 7a81b07

Browse files
committed
Add Converter class that includes string converters extension methods
1 parent e6e0fba commit 7a81b07

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Helpers/Converters.cs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.IO;
4+
using System.Text;
5+
6+
namespace SafeCrypt
7+
{
8+
public static class Converters
9+
{
10+
public static string ByteArrayToHexString(this byte[] bytes)
11+
{
12+
StringBuilder hex = new StringBuilder(bytes.Length * 2);
13+
foreach (byte b in bytes)
14+
hex.AppendFormat("{0:x2}", b);
15+
return hex.ToString();
16+
}
17+
18+
public static string BytesToString(this byte[] bytes)
19+
{
20+
using (MemoryStream stream = new MemoryStream(bytes))
21+
{
22+
using (StreamReader streamReader = new StreamReader(stream))
23+
{
24+
return streamReader.ReadToEnd();
25+
}
26+
}
27+
}
28+
29+
public static byte[] HexadecimalStringToByteArray(this string input)
30+
{
31+
var outputLength = input.Length / 2;
32+
var output = new byte[outputLength];
33+
using (var sr = new StringReader(input))
34+
{
35+
for (var i = 0; i < outputLength; i++)
36+
output[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(),
37+
(char)sr.Read() }), 16);
38+
}
39+
return output;
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)