Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Crafting on Hex String

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
29 Oct 2014CPOL1 min read 7.7K   3  
Crafting on hex string

Image 1

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:

VB.NET
'this is the worst hex string that I've ever wrote =)
Dim SourceHex as String = "DE;51:C6 49-3E+99=73&D4#DC@A5*1A_9B\3C<C2>7E/7C"
'but it's readable!

'and this is the set of expecting chars.
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 chars in source string:

VB.NET
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:

VB.NET
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --