Hello there! Today we'll go to the Dark Side of Power to get control of hexadecimal strings and improve your skill.
Let's Start
A perfect hex string is strictly limited to character set, which consists of the symbols {0 ... 9, a ... f, A...F} and a delimiter char.
This is the standard version. In other words, it is an ideal.
But what if source hexadecimal string contains one or more errors occurred due to a faulty scanner or casual misprint? What if the source has a delimiter character different from delimiter in your program?
Q: How can I get all the delimiters from hex string?
A: First of all, let's define a source string and a set of 'correct' hex chars:
Dim SourceHex as String = "DE;51:C6 49-3E+99=73&D4#DC@A5*1A_9B\3C<C2>7E/7C"
Dim GoodChars() As Char = New Char() {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f",
"A", "B", "C", "D", "E", "F"}
So, to get all delimiters, we'll just exclude this correct char
from huge amount of char
s in source string:
Dim DelimChars() As Char = SourceHex.Except(GoodChars).ToArray
Q: I don't need a ton of delimiters. How can I get an array of useful bytes?
A: Piece of cake! Just split source string with that ugly amount of delimiters:
Dim UsefulData() As String = SourceHex.Split(DelimChars)
In this step, we got data cleaned of any trash. However, it may still contain errors. For example, two or more bytes without delimiter (following each other).
So you have to check all the items in array and try to correct found errors (inserting separator between "glued" bytes).
If errors were found, you need to join array items using same delimiter and split resulting string again with one (if needed to get Byte()
).
Hope this helps.