Add test for hex string (arbitrary length) convert

This commit is contained in:
Kurt 2021-05-09 23:33:54 -07:00
parent 1cad57e35d
commit 01f75f8441
3 changed files with 23 additions and 9 deletions

View file

@ -123,15 +123,20 @@ namespace PKHeX.Core
public static byte[] GetBytesFromHexString(string seed) public static byte[] GetBytesFromHexString(string seed)
{ {
return Enumerable.Range(0, seed.Length) byte[] result = new byte[seed.Length / 2];
.Where(x => x % 2 == 0) for (int i = 0; i < result.Length; i++)
.Select(x => Convert.ToByte(seed.Substring(x, 2), 16)) {
.Reverse().ToArray(); var slice = seed.Substring(i * 2, 2);
result[i] = Convert.ToByte(slice, 16);
}
Array.Reverse(result);
return result;
} }
public static string GetHexStringFromBytes(byte[] data, int offset, int length) public static string GetHexStringFromBytes(byte[] data, int offset, int length)
{ {
data = data.Skip(offset).Take(length).Reverse().ToArray(); data = data.Slice(offset, length);
Array.Reverse(data);
return BitConverter.ToString(data).Replace("-", string.Empty); return BitConverter.ToString(data).Replace("-", string.Empty);
} }

View file

@ -49,12 +49,11 @@ namespace PKHeX.Tests.PKM
CheckStringGetSet(nameof(pkm.Nickname), name_nidoran, pkm.Nickname, byte_nidoran, pkm.Nickname_Trash); CheckStringGetSet(nameof(pkm.Nickname), name_nidoran, pkm.Nickname, byte_nidoran, pkm.Nickname_Trash);
} }
private static void CheckStringGetSet(string check, string instr, string outstr, byte[] indata, private static void CheckStringGetSet(string check, string instr, string outstr, byte[] indata, byte[] outdata)
byte[] outdata)
{ {
instr.Should().BeEquivalentTo(outstr); instr.Should().BeEquivalentTo(outstr);
outdata = outdata.Take(indata.Length).ToArray(); outdata = outdata[..indata.Length];
indata.SequenceEqual(outdata).Should() indata.SequenceEqual(outdata).Should()
.BeTrue($"expected {check} to set properly, instead got {string.Join(", ", outdata.Select(z => $"{z:X2}"))}"); .BeTrue($"expected {check} to set properly, instead got {string.Join(", ", outdata.Select(z => $"{z:X2}"))}");

View file

@ -1,4 +1,5 @@
using FluentAssertions; using System;
using FluentAssertions;
using Xunit; using Xunit;
namespace PKHeX.Tests.Util namespace PKHeX.Tests.Util
@ -34,5 +35,14 @@ namespace PKHeX.Tests.Util
var convert = Core.Util.GetHexValue(v); var convert = Core.Util.GetHexValue(v);
convert.Should().Be(result); convert.Should().Be(result);
} }
[Theory]
[InlineData("01020304", 0x1020304)]
public void CheckConvertHexString(string v, uint result)
{
var convert = Core.Util.GetBytesFromHexString(v);
var u32 = BitConverter.ToUInt32(convert);
u32.Should().Be(result);
}
} }
} }