String to Hex Conversion Using Vb.Net - vb.net-2010

Im trying to Convert Hexadecimal value to String but i dont know how to do.
This what i tried to do but it's Int to Hex.
sHex = Hex(Text)
TextBox2.Text = sHex

Try this
Function StringToHex(ByVal text As String) As String
Dim hex As String
For i As Integer = 0 To text.Length - 1
hex &= Asc(text.Substring(i, 1)).ToString("x").ToUpper
Next
Return hex
End Function
use it with the console.
Debug.WriteLine(StringToHex("sim0n"))
let me know if it works for u.

Related

How do I convert a floating point to hexadecimal in VB.NET?

Example: The float value is -1580.719 and I need to convert it to hex in VB.NET (Value in hex should output: C4C59704).
Ok, so I found how to do it:
Dim var As Single = Single.Parse("-1580.719")
Dim varArray() As Byte = BitConverter.GetBytes(var)
Array.Reverse(varArray)
Dim result As String = BitConverter.ToString(varArray).Replace("-", "")
Value of result is:
C4C59702

Dealing with null character in VB.NET

I am trying to open a binary file in VB.NET (Visual Studio 2010), that looks like this:
The file opens ok with this method:
Dim OpenFile1 As New OpenFileDialog
If (OpenFile1.ShowDialog = System.Windows.Forms.DialogResult.OK And (OpenFile1.FileName.Length > 0)) Then
'do something
End If
However, if "do something" is:
Dim readText As String = File.ReadAllText(OpenFile1.FileName)
MsgBox(readText)
Only the first byte is converted, as the second one is 00 (null) and truncates the rest of the file, marking the end of the string, and it displays only the first byte F0 (≡ in ASCII).
But if I do:
'convert file to hex string
Dim bytes As Byte() = IO.File.ReadAllBytes(OpenFile1.FileName)
Dim hex As String() = Array.ConvertAll(bytes, Function(b)
b.ToString("X2"))
Dim newfile As String
newfile = (String.Join("", hex))
RichTextBox1.Text = newfile
Now the string is properly converted to hex values. So far so good.
However, when I try to convert the string back to ASCII using this method:
'convert hex string to text and put it into the richtextbox
Dim asciistring As String = ""
For x As Integer = 0 To (newfile.Length - 1) Step 2
Dim k As String = newfile.Substring(x, 2)
asciistring &= System.Convert.ToChar(System.Convert.ToUInt32(k,
16)).ToString()
Next
RichTextBox1.Text = asciistring
Again, only the first byte is converted. The rest is truncated as soon as it finds a 00 (null).
Is there a way to circumvent this situation?
Haven't tested out this code yet, but you can try give this method a try :
Public Shared Function ConvertHex(ByVal hexString As String) As String
Try
Dim ascii As String = String.Empty
For i As Integer = 0 To hexString.Length - 1 Step 2
Dim hs As String = String.Empty
hs = hexString.Substring(i, 2)
Dim decval As UInteger = System.Convert.ToUInt32(hs, 16)
Dim character As Char = System.Convert.ToChar(decval)
ascii += character
Next
Return ascii
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return String.Empty
End Function
When calling the function, just pass your hex string.

Convert string of byte array back to original string in vb.net

I have a plain text string that I'm converting to a byte array and then to a string and storing in a database.
Here is how I'm doing it:
Dim b As Byte() = System.Text.Encoding.UTF8.GetBytes("Hello")
Dim s As String = BitConverter.ToString(b).Replace("-", "")
Afterwards I store the value of s (which is "48656C6C6F") into a database.
Later on, I want to retrieve this value from the database and convert it back to "Hello". How would I do that?
You can call the following function with your hex string and get "Hello" returned to you. Note that the function doesn't validate the input, you would need to add validation unless you can be sure the input is valid.
Private Function HexToString(ByVal hex As String) As String
Dim result As String = ""
For i As integer = 0 To hex.Length - 1 Step 2
Dim num As Integer = Convert.ToInt32(hex.Substring(i, 2), 16)
result &= Chr(num)
Next
Return result
End Function
James Thorpe points out in his comment that it would be more appropriate to use Encoding.UTF8.GetString to convert back to a string as that is the reverse of the method used to create the hex string in the first place. I agree, but as my original answer was already accepted, I hesitate to change it, so I am adding an alternative version. The note about validation of input being skipped still applies.
Private Function HexToString(ByVal hex As String) As String
Dim bytes(hex.Length \ 2 - 1) As Byte
For i As Integer = 0 To hex.Length - 1 Step 2
bytes(i \ 2) = Byte.Parse(hex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber)
Next
Return System.Text.Encoding.UTF8.GetString(bytes)
End Function

Convert Arabic string to an array of bytes

I have a function which converts string to an array of bytes. If the string is written in English, the function works fine. But if the input string is Arabic, the function doesn't return, and I get this error:
Value was either too large or too small for an unsigned byte
Friend Function StringtoByteArray(ByRef value As String) As Byte()
Dim temp() As Byte
ReDim temp(Len(value) - 1)
Dim i As Integer
For i = 0 To Len(value) - 1 Step 1
temp(i) = Convert.ToByte(Convert.ToChar(Mid(value, i + 1, 1)))
Next
StringtoByteArray = temp
End Function
What should I change to convert Arabic characters to byte?
I am using VB.NET.
You don't need to write your function for that, this should work:
Dim b As Byte() = System.Text.Encoding.Unicode.GetBytes(value)

Mixed Encoding to String

I have a string in VB.net that may contain something like the following:
This is a 0x000020AC symbol
This is the UTF-32 encoding for the Euro Symbol according to this article http://www.fileformat.info/info/unicode/char/20ac/index.htm
I'd like to convert this into
This is a € symbol
I've tried using UnicodeEncoding() class in VB.net (Framework 2.0, as I'm modifying a legacy application)
When I use this class to encode, and then decode I still get back the original string.
I expected that the UnicodeEncoding would recognise the already encoded part and not encode it against. But it appears to not be the case.
I'm a little lost now as to how I can convert a mixed encoded string into a normal string.
Background: When saving an Excel spreadsheet as CSV, anything outside of the ascii range gets converted to ?. So my idea is that if I can get my client to search/replace a few characters, such as the Euro symbol, into an encoded string such as 0x000020AC. Then I was hoping to convert those encoded parts back into the real symbols before I insert to a SQL database.
I've tried a function such as
Public Function Decode(ByVal s As String) As String
Dim uni As New UnicodeEncoding()
Dim encodedBytes As Byte() = uni.GetBytes(s)
Dim output As String = ""
output = uni.GetString(encodedBytes)
Return output
End Function
Which was based on the examples on the MSDN at http://msdn.microsoft.com/en-us/library/system.text.unicodeencoding.aspx
It could be that I have a complete mis-understanding of how this works in VB.net. In C# I can simply use escaped characters such as "\u20AC". But no such thing exists in VB.net.
Based on advice from Heinzi I implemented a Regex.Replace method using the following code, this appear to work for my examples.
Public Function Decode(ByVal s As String) As String
Dim output As String = ""
Dim sRegex As String = "0x[0-9a-zA-Z]{8}"
Dim r As Regex = New Regex(sRegex)
Dim myEvaluator As MatchEvaluator = New MatchEvaluator(AddressOf HexToString)
output = r.Replace(s, myEvaluator)
Return output
End Function
Public Function HexToString(ByVal hexString As Match) As String
Dim uni As New UnicodeEncoding(True, True)
Dim input As String = hexString.ToString
input = input.Substring(2)
input = input.TrimStart("0"c)
Dim output As String
Dim length As Integer = input.Length
Dim upperBound As Integer = length \ 2
If length Mod 2 = 0 Then
upperBound -= 1
Else
input = "0" & input
End If
Dim bytes(upperBound) As Byte
For i As Integer = 0 To upperBound
bytes(i) = Convert.ToByte(input.Substring(i * 2, 2), 16)
Next
output = uni.GetString(bytes)
Return output
End Function
Have you tried:
Public Function Decode(Byval Coded as string) as string
Return StrConv(Coded, vbUnicode)
End Function
Also, your function is invalid. It takes s as an argument, does a load of stuff and then outputs the s that was put into it instead of the stuff that was processed within it.