Skip to content

Commit

Permalink
Extended ByteHelper class
Browse files Browse the repository at this point in the history
  • Loading branch information
hannesbarbez committed May 6, 2022
1 parent c26cffa commit ff6c400
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<Authors>Hannes Barbez</Authors>
<Company>Hannes Barbez</Company>
<Title>BarbezDotEu.Byte</Title>
Expand Down
2 changes: 1 addition & 1 deletion BarbezDotEu.Byte/BarbezDotEu.Byte/BarbezDotEu.Byte.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<Product>BarbezDotEu.Byte</Product>
<PackageId>BarbezDotEu.Byte</PackageId>
<Copyright>©2022 Hannes Barbez</Copyright>
<Version>2.0.0</Version>
<Version>2.1.0</Version>
<Description>Generic logic pertaining to byte and byte arrays.</Description>
<PackageTags>byte, byte array</PackageTags>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
Expand Down
32 changes: 32 additions & 0 deletions BarbezDotEu.Byte/BarbezDotEu.Byte/ByteHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) Hannes Barbez. All rights reserved.
// Licensed under the GNU General Public License v3.0

using System;
using System.Linq;
using System.Text;

namespace BarbezDotEu.Byte
Expand All @@ -24,5 +26,35 @@ public static byte[] ToByteArray(this string input, Encoding encoding = default)

return encoding.GetBytes(input);
}

/// <summary>
/// Converts a "written" byte-array to an actual byte array.
/// e.g. input string: 69CC766AEFAE05F6BE92A529E27D6AC50A0DC73EFB3631534B5E41A9311D56AB.
/// </summary>
/// <param name="hex">The "written" byte-array to convert.</param>
/// <returns>The actual byte-array representation.</returns>
/// <remarks>Based on https://stackoverflow.com/a/321404/8669939</remarks>
public static byte[] StringToByteArray(this string hex)
{
// TODO: Check what can and cannot be merged with ToByteArray method above, and rename or remove accordingly if needed.
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}

/// <summary>
/// Generates a string representation of a byte array.
/// </summary>
/// <param name="hash">The hash to write as string.</param>
/// <returns>A string representation of the hash.</returns>
public static string ByteArrayToString(byte[] hash)
{
var stringBuilder = new StringBuilder(hash.Length * 2);
foreach (byte @byte in hash)
stringBuilder.Append(@byte.ToString("X2"));

return stringBuilder.ToString();
}
}
}

0 comments on commit ff6c400

Please sign in to comment.