1 //
2 // Copyright (c) 2010-2025 Antmicro
3 //
4 // This file is licensed under the MIT License.
5 // Full license text is available in 'licenses/MIT.txt'.
6 //
7 
8 using NUnit.Framework;
9 using System;
10 
11 namespace Antmicro.Renode.Utilities
12 {
13     [TestFixture]
14     public class MiscTests
15     {
16         [Test]
ShouldGetBytesFromHexString()17         public void ShouldGetBytesFromHexString()
18         {
19             Assert.AreEqual(new byte[] {0x0a}, Misc.HexStringToByteArray("0a"));
20             Assert.AreEqual(
21                 new byte[] {0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89},
22                 Misc.HexStringToByteArray("abcdefABCDEF0123456789")
23             );
24             Assert.AreEqual(new byte[] {0x0a, 0xb1}, Misc.HexStringToByteArray("0aB1"));
25             Assert.AreEqual(new byte[] {0xb1, 0x0a}, Misc.HexStringToByteArray("0aB1", reverse: true));
26             Assert.AreEqual(new byte[] {0x00, 0xab, 0x15}, Misc.HexStringToByteArray("00aB15"));
27             Assert.AreEqual(new byte[] {0x15, 0xab, 0x00}, Misc.HexStringToByteArray("00aB15", reverse: true));
28             Assert.AreEqual(new byte[] {0xab}, Misc.HexStringToByteArray("a\tb", ignoreWhitespace: true));
29             Assert.AreEqual(new byte[] {0xab}, Misc.HexStringToByteArray("a\t \nb", ignoreWhitespace: true));
30             Assert.AreEqual(new byte[] {0xab, 0xcd}, Misc.HexStringToByteArray("ab cd", ignoreWhitespace: true));
31             Assert.AreEqual(new byte[] {0xcd, 0xab}, Misc.HexStringToByteArray("ab cd", ignoreWhitespace: true, reverse: true));
32             Assert.AreEqual(new byte[] {0xab, 0xcd, 0xef}, Misc.HexStringToByteArray("abc def", ignoreWhitespace: true));
33             Assert.AreEqual(new byte[] {0xef, 0xcd, 0xab}, Misc.HexStringToByteArray("abc def", ignoreWhitespace: true, reverse: true));
34 
35             Assert.Throws<FormatException>(
36                 () => {
37                     Misc.HexStringToByteArray("ab3");
38                 }
39             );
40             Assert.Throws<FormatException>(
41                 () => {
42                     Misc.HexStringToByteArray("ab cd");
43                 }
44             );
45             Assert.Throws<FormatException>(
46                 () => {
47                     Misc.HexStringToByteArray("abc def");
48                 }
49             );
50             Assert.Throws<FormatException>(
51                 () => {
52                     Misc.HexStringToByteArray("x");
53                 }
54             );
55             Assert.Throws<FormatException>(
56                 () => {
57                     Misc.HexStringToByteArray("xx");
58                 }
59             );
60         }
61     }
62 }
63