Skip to content

Commit

Permalink
HexStringConverter: implement grouping
Browse files Browse the repository at this point in the history
  • Loading branch information
akopetsch committed Jun 4, 2024
1 parent 205b73d commit 373b5b7
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
7 changes: 7 additions & 0 deletions ByteSerialization.Tests/Unit/IO/HexStringConverterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace ByteSerialization.Tests.Unit.IO
public class HexStringConverterTest
{
private const string hexString = "deadbeef";
private const string hexString_groupSize2 = "dead beef";
private static readonly byte[] byteArray = [0xDE, 0xAD, 0xBE, 0xEF];

[Fact]
Expand All @@ -23,5 +24,11 @@ public void Test_ToHexString() =>
Assert.Equal(
expected: hexString,
actual: HexStringConverter.ToHexString(byteArray));

[Fact]
public void Test_ToHexString_groupSize2() =>
Assert.Equal(
expected: hexString_groupSize2,
actual: HexStringConverter.ToHexString(byteArray, groupSize: 2));
}
}
2 changes: 1 addition & 1 deletion ByteSerialization/ByteSerialization.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Nullable>disable</Nullable>
<Authors>Alexander Kopetsch</Authors>
<Version>0.0.1.0</Version>
<PackageVersion>0.0.1-alpha.2</PackageVersion>
<PackageVersion>0.0.1-alpha.3</PackageVersion>
<PackageProjectUrl>https://github.com/akopetsch/ByteSerialization</PackageProjectUrl>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
Expand Down
12 changes: 10 additions & 2 deletions ByteSerialization/IO/HexStringConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ namespace ByteSerialization.IO
{
public static class HexStringConverter
{
private const string Space = " ";

public static byte[] ToByteArray(string hexString)
{
string s = hexString.Replace(" ", string.Empty);
string s = hexString.Replace(Space, string.Empty);
byte[] byteArray = new byte[s.Length / 2];
for (int i = 0; i < byteArray.Length; i++)
byteArray[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);
Expand All @@ -27,11 +29,17 @@ public static string ToCompactHexString(this long value)
"0" + s : s;
}

public static string ToHexString(this byte[] bytes)
public static string ToHexString(this byte[] bytes, int? groupSize = null)
{
var result = new StringBuilder(bytes.Length * 2);
for (int i = 0; i < bytes.Length; i++)
{
// group?
if (i != 0 && groupSize.HasValue && i % groupSize.Value == 0)
result.Append(Space);

result.Append(bytes[i].ToString("x2"));
}
return result.ToString();
}
}
Expand Down

0 comments on commit 373b5b7

Please # to comment.