This is a mirror of official site: http://jasper-net.blogspot.com/

Converting Hex String To Corresponding Byte Array Using C#

| Monday, July 30, 2012
I came across an issue where I needed to convert a string representing HEX value into corresponding byte array. I know that there are various solutions that all accomplish the same task: Take A String And Convert It To Equivalent Byte Array.

For example a string value: 0x0123456789ABCDEF would be 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD and 0xEF represented in a byte array. The basic .NET functions would give you the byte array of the actualy ASCII characters, and not the binary value that they represent. There was all kind of solutions out there. Some declared to be faster than other, or simply the fastest. I am sure the solution that I came up with is not prettiest or the most effcient. But, it is my solution that I came up with. I am sure that it has been thought before but have not seen any post that are quite a like it. I think that it is pretty good solution for what I wanted to accomplish. That said. I love learning. So, if you find a problem or have an idea to improve it. Please! All feedback is welcomed: The Good, The Bad and The Ugly.

The Problem

Convert a string it to a byte array representing the actual text values of each byte.

Considerations

I spent some time thinking about different things that I would have to take into consideration when doing the conversion of the string to the byte array.

Special Cases: Input is valid, and expected but it creates special handling conditions.

Is the input string null or empty
The string starts with the HEX indicator string '0x'.
Is the leading '0' dropped from the string.
The casing of the letter, they can be upper, lower or mixed casing.
Error Checking: We live in a World where we can't trust any, not even our input string. So, I need to have some type of validation in place for the input.

Does the string contain characters that are not valid alphanumeric values: 0-9 and A-F.
Approach

Taking into account the factors that I came up with, I came up with the following approach.

To handle the case of null or empty input, I would return an empty array. To avoid, unnecessary allocations I created a static, readonly empty byte array that I would return to the caller.

private static readonly byte[] Empty = new byte[0];
Once I have determined that I actually have some type of string. I would handle rest of conditions during the conversion, except the 'dropped' leading zero ('0') which I would handle before the actual conversion.

Read more: Heikki Ritvanen
QR: Inline image 1

Posted via email from Jasper-net

0 comments: