Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# Hex to byte converter

Posted on 2011-03-11
Medium Priority
1,322 Views
Ive written a simple line which converts a byte array to a hex string:-
urlSafe = BitConverter.ToString(byt2Convert).Replace("-", "")

However I have no idea how to convert back to a byte array? Does anyone?

I cant seem to find any example code as simple as converting it from byte to string.

Any ideas?

Thank you
0
Question by:tonelm54
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 7

Expert Comment

ID: 35107977
Straight from http://stackoverflow.com/questions/321370/convert-hex-string-to-byte-array
``````public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length).
Where(x => 0 == x % 2).
Select(x => Convert.ToByte(hex.Substring(x, 2), 16)).
ToArray();
}
``````
0

LVL 41

Expert Comment

ID: 35109185
Here is another similar technique that doesn't use lamba expressions

``````' There's no easy way to convert a hex byte string back into
' a byte array, so we have parse each byte
ReDim in_buf((message.Length \ 2) - 1)
For i As Integer = 0 To in_buf.Length - 1
in_buf(i) = Byte.Parse(message.Substring(i * 2, 2), Globalization.NumberStyles.HexNumber)
Next
``````
0

LVL 3

Accepted Solution

1303gun earned 2000 total points
ID: 35116609
You can also try this alternative. Just call Hex2Byte and specify the hex string as parameter.
``````Function Hex2Byte(ByVal Hex As String) As Byte()
Dim bytes As New List(Of Byte)
For i As Integer = 0 To Hex.Length - 1 Step 2
Next
Return bytes.ToArray
End Function
``````
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
###### Suggested Courses
Course of the Month8 days, 8 hours left to enroll