I have a hex type data which is "0x0A7A" which I converted to a string. Now I want to convert it back to hex. Meaning the "0x0A7A" which was a string earlier will be back to "0x0A7A" as hex. How can I do it in VB.NET 2010?
-
[How do you convert a string into Hexadecimal in vb.net](http://stackoverflow.com/questions/10504034/how-do-you-convert-a-string-into-hexadecimal-in-vb-net) – Justin Ryan Nov 13 '14 at 09:14
-
3There is no such thing as a hex data type. Please show the code you have already and try to explain your requirement in more detail – Matt Wilko Nov 13 '14 at 09:21
-
I agree with @MattWilko there is no representation of hex. If you had this line in your code: `byte value = 0xFF` or `Dim value as Byte = 0xFF`, and then printed the byte value within a textbox, you would see this: `255`. – Ckrempp Nov 13 '14 at 16:37
-
Yep, My bad.. it is a byte[] type data.. which contains a hex data type from database. – Lucas Juan Nov 14 '14 at 01:33
2 Answers
I want to convert it back to hex. Meaning the "0x0A7A" which was a string earlier will be back to "0x0A7A" as hex. How can I do it in VB.NET 2010?
You mean?
Private OriginalInt32 As Int32 = &h0A7A
Private SomeString As String = "0x" + OriginalInt32.ToString("X4") ' holds "0x0A7A"
' And get a value
Private SomeInt As Int32 = HexToInt32(SomeString) ' Returns &h0A7A
' where HexToInt32() is some sort of function that returns a Value
Public Function HexToInt32(ByVal SourceString As String) As Int32
' Parse the string:
' - Kill leading "0x"
' - Assume default endianness then read each char pair from the right
' -> "7A" and "0A" and stop
' - Convert those to some Int32 numeric
' - Use bitwise shift
' - Return the sum
End Function
First, there is no such thing as hex type data in .NET, or I'm missing something? You have Int32, UShort, Double, String, Char, Object, CustomClass, etc...
0x0A7A could be any value, depending on the type of the variable storing it. That is, you can't know for sure what 0x0A7A is for us as humans if you don't know which variable contains it.
Let's take an Int32.
If you write Dim MyInt32 As Int32 = &h0A7A
, this integer holds the value 2682 no matter what's the endianness of your system. (Note: in Visual Basic, you write an explicit hex value in the IDE using "&H____")
You would then want to convert MyInt32 to string (for displaying purposes?) and that's where everything goes bad. An Int32 is four bytes, each byte requiring two hex digits to represent the 256 possibles values.
- On a big-endian CPU architecture, you'll get "00-00-0A-7A" => "0x00000A7A"
- On a little-endian (mine for instance), you'll get "7A-0A-00-00" => "0x7A0A0000"
While you're on the same computer (that is, not sending the string data to the network) you can write and read hex<->Int32 both ways without any problems, assuming your function that converts back and forth can handle any provided number of pair-digits hex data:
"0x0A7A", "0x000A7A", "0x00000A7A" => always 2682 Int32 value (your system is BigEndian)
ToString()
Hopefully, you have ToString
that can convert any of the base numeric type to a string representation as hex! The good thing is: ToString("X") outputs values in big-endian. Yes, it defaults you to use big-endian, but does that really matter?
Also note that:
Dim SomeInt As Int32 = &h0A7A
MessageBox.Show(SomeInt.ToString("X"))
' -> Outputs "A7A"
Yes, that looks weird, but hold on, since you know you would need eight hex characters to represent an Int32, you can do this:
MessageBox.Show(SomeInt.ToString("X8"))
' -> Outputs "00000A7A"
' "0x" + SomeInt.ToString("X4") -> "0x0A7A"
Of course, if the required number of hex characters is greater than the specified digit in the ToString parameter, the outputted string will be longer than expected. That's also why you should not always assume the hex representation of something as String comes with several nice pair of hex characters. "0xA7A" is a valid hex representation of the Int32 2682.
=> That's why you must know which type you're manipulating and control the way to get its hex representation. Otherwise, talking about Hex data type doesn't mean anything...
So, now you're going to edit your question, to mention the actual type of the data...
Maybe you're looking for converting
Char
Type to hex and back to Char ?
By the way, CharCode 0x0A7A is this in Unicode: ?? :/ ??
Uh-ho! Char doesn't have an inbuilt .ToString("X4")
:/ I assume you want to manipulate Strings? Numbers can be easily converted to hex, but Strings are the ones that drive people crazy...
Soooo, how then?
Let's make one thing clear: there are hundreds of ways to convert something to its hex representation.
But talking about Char, or String, to be converted to hex, a minimum knowledge of what a char is is required: You have millions of different actual chars in the world. Then, you must choose the appropriate encoding in order to be able to represent all chars you may encounter in your application. Otherwise, you'll get garbage on screen or worse, corrupted data.
Converting a char to its hex representation as string also depends on the selected encoding. Don't think each char is always a pair of bytes.
- That's not the case with ASCII encoding: one byte
- Not the case in UTF-8: one to four bytes
- And not even the case in UTF-16: one charater you see on screen could be stored as two consecutive chars in your String variable, so while you're seeing only one character, your string length is 2: four bytes.
Without defining the encoding prior anything, you'll get in trouble.
If I'm not mistaken, strings in .NET are stored in memory in UTF-16 encoding. That means if you convert a string in its hex representation using the available classes in the .NET reference, you don't have to bother about endianness. And you don't have to bother looking for another encoding to convert the hex to string, just use the Unicode encoding provided by .NET.
But that's where one nasty thing comes in: Performance!
I won't tell you which one of the answers in the link I posted above is the best. Performance is relative. Sometimes a piece of code proved slower took alone in billion loops will perform well when it suits the application requirements (for example, the parameter used is already available while other approaches require more types conversion).
Have a look at the linked Stack Overflow question as well as each realated Stack Overflow topic. I'm (pretty) sure you'll get what you want. You may also have a look at Char.ConvertFromUtf32()
and ConvertToUtf32()
documentation. ConvertFromUtf32 will give you as String
because .NET is UTF-16 and can't represent chars above 0xFFFF. To represent such chars, .NET must actually write two chars, which are called surrogate pairs, and count for two char in String.Length, but they are actually displayed as one single char on the screen.
And you can have a look at BitConverter which has the nice GetBytes(Int32) function. If you plan to have total control over byte ordering or go UTF-32, it may help.
By the way, talking about String and encodings, you should read the documentation about, or at least Encoding.GetString(
SomeArrayOfBytes)
.
Be sure of what you want to do or you'll get Too broad question flagging. Sometimes, it's not necessary to convert everything to hex representation as string. An array of Bytes will suffice. At the moment, your question is unclear:
- It doesn't really define a context
- It doesn't clearly highlight the goal because the required elements to start with are missing (what's the type of your variable)
- It doesn't give hints on the preferred path to reach the goal (which tools? Char? ToString()? Array of Byte? ...)
I can't correctly guess if those approaches are relevant or not:
Private p_HexArray As String() = _
{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}
' Very simple Byte to Hex (very slow..)
<Extension()>
Public Function ToHex(ByVal SourceByte As Byte) As String
Return p_HexArray(SourceByte \ 16) + p_HexArray(SourceByte Mod 16)
End Function
' Very simple Int32 to Hex (very slow..)
<Extension()>
Public Function ToHex(ByVal SourceInt32 As Int32) As String
Dim Int32Bytes As Byte() = BitConverter.GetBytes(SourceInt32)
Return Int32Bytes(0).ToHex() + Int32Bytes(1).ToHex() + _
Int32Bytes(2).ToHex() + Int32Bytes(3).ToHex()
End Function
' Very simple Char to Hex (very slow)
Char.ConvertToUtf32(MyChar.ToString(), 0).ToString("X4")
' Very simple String Data to Hex (very slow !!!!!!!!!!!!!!!!!!!!)
Dim CurrentString As String = "Coco"
Dim CurrentEncoding As Encoding = New System.Text.UnicodeEncoding()
Dim Allbytes As Byte() = CurrentEncoding.GetBytes(CurrentString)
Dim sb As New System.Text.StringBuilder()
For Each CurrentByte As Byte In AllBytes
sb.Append(CurrentByte.ToHex()) ' Using Extension above
Next
Return sb.ToString()
' ....
Then, when you understand what the tools are, what they do, what they are manipulating, and you get a clear picture of what you want to do, you can go on with optimizations and replace all the above with one of the other answers from other questions here, using bitwise shiftings, structure pointers, both managed and unmanaged code.

- 1
- 1

- 1,120
- 8
- 22
As already stated by other members, hexadecimal is a text representation, not a data type: it is one of the formats you can use to display or store numeric values as text.
By the way, when someone have such a text value representation, it is very common to convert it back into a numeric data type, like integers.
I like very much the answer by fsintegral, but it is missing the most common solution:
Assuming that the original type was an Integer and you are sure about the validity of the hex string (starting always with "0x", containing only valid digits and letters, and producing a value between the Integer range), you can try something like:
Imports System.Globalization
'' Existing class declarations / methods declarations / code
Public Function IntFromHex(ByVal text As String) As Integer
Return Integer.Parse(text.Substring(2), NumberStyles.AllowHexSpecifier)
End Function
If instead you do not have guarantees about text validity, you can try:
Imports System.Globalization
'' Existing class declarations / methods declarations / code
Public Function IntFromHex(ByVal text As String) As Integer
If text.StartsWith("0x") Then
text = text.Substring(2)
End If
Dim value As Integer
If Not Integer.TryParse(text, NumberStyles.AllowHexSpecifier, Nothing, value) Then
'' Handle Bad format here
'' Return 0
End If
Return value
End Function
More information is at Int32.TryParse Method (MSDN).

- 30,738
- 21
- 105
- 131

- 661
- 6
- 12