473,226 Members | 1,299 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,226 software developers and data experts.

How to convert hex to string?

Hi!

I've made little code to convert string into hex string...

Public ReadOnly Property ToHexString(ByVal text As String) As String
Get
Dim arrBytes As Integer() = CharsToBytes(text)
Dim sb As StringBuilder = New StringBuilder

For i As Integer = 0 To arrBytes.Length - 1
'// If it's a single digit, append a zero in front of it.
If (Hex(arrBytes(i)).Length = 1) Then
sb.Append("0" + Hex(arrBytes(i)))
Else
sb.Append(Hex(arrBytes(i)))
End If
Next

Return sb.ToString()
End Get
End Property

Private Function CharsToBytes(ByVal text As String) As Integer()
Dim c As Char() = text.ToCharArray()
Dim arrBytes As Integer()
ReDim arrBytes(c.Length() - 1)

For i As Integer = 0 To c.Length() - 1
arrBytes(i) = System.Convert.ToByte(c(i))
Next

Return arrBytes
End Function

.... and it's working fine. For example my name "MIKA" will be "4D494B41"
as hex string, but I don't find out how to do this opposite way? I mean
how to get "MIKA" of "4D494B41" hex string.

Other question: It's possible to change when using VB like...

Asc(c(i)) -> System.Convert.ToByte(c(i))

.... is there also same kind of way for Hex()-function?

--
Thanks in advance!

Mika
Nov 21 '05 #1
5 37162
Mika M wrote:
... and it's working fine. For example my name "MIKA" will be
"4D494B41" as hex string, but I don't find out how to do this
opposite way? I mean how to get "MIKA" of "4D494B41" hex string.


Here's one way to do it:

\\\
Private Function DecodeHex(ByVal HexString As String) As String
Dim thisChar As String
Dim ascii As Integer
Dim ret As String
'Keep going until we exhaust all the source string
Do While Len(HexString) > 0
'Get the next two-digit hex number
thisChar = HexString.Substring(0, 2)
'Remove this hex number from the source string
HexString = HexString.Substring(2)
'Get the value in decimal of this hex number
ascii = CInt(Val("&H" & thisChar))
'Convert it to a character
ret &= Chr(ascii)
Loop
'All done
Return ret
End Function
///

Call this with "4D494B41" as the HexString parameter value and it will
return "MIKA".

It works by using a handy feature of the Val() command. If you pass a number
prefixed with "&H", it will treat that as a hex number when it parses it. So
if you ask it for Val("&H10"), it will return 16.

The code simply loops through each pair of characters (each 8-bit hex value)
and decodes the value to a number. It then gets the ASCII character
represented by this number.

There's no validation or anything so you'll need to add that yourself if
there's a chance of passing non-hex values to the function.

Hope that helps,

--

(O) e n o n e
Nov 21 '05 #2
Here's a shortened version of part of your existing code:

You will notice that {0:X2} makes sure you always have 2 chars & you won't
need to add your zero to the beginning

Public Function ToHexString(ByVal sText As String) As String

Dim arrBytes As Integer() = CharsToBytes(sText)
Dim sb As StringBuilder = New StringBuilder

For i As Integer = 0 To arrBytes.Length - 1
sb.Append(String.Format("{0:x2}", Hex(arrBytes(i))))
Next

Return sb.ToString()
End Function

Crouchie1998
BA (HONS) MCP MCSE
Nov 21 '05 #3
Mika,

I have created two functions of my own which will be better for you. The
zipped project is also attached if you want to download it. Otherwise,
follow thses instructions:

1) Create a new Windows application
2) Add a button
3) Add this import:
Imports System.text
4) Now, paste in the following functions:

Private Function EncodeHexString(ByVal sText As String) As String
Dim intLength As Integer = sText.Length
If (intLength = 0) Then Return ""
Dim intCount As Integer = 0
Dim sb As New StringBuilder(intLength * 2)
Dim bBytes() As Byte = System.Text.Encoding.ASCII.GetBytes(sText)
For intCount = 0 To bBytes.Length - 1
sb.AppendFormat("{0:X2}", bBytes(intCount))
Next
Return sb.ToString()
End Function

Private Function DecodeHexString(ByVal sText As String) As String
Dim intLength As Integer = sText.Length
If (intLength = 0) Then Return ""
Dim intCount As Integer = 0
Dim sb As New StringBuilder(CType(intLength / 2, Integer))
Try
For intCount = 0 To sText.Length - 1 Step 2
sb.Append(Convert.ToChar(Byte.Parse(sText.Substrin g(intCount,
2), Globalization.NumberStyles.HexNumber)))
Next
Catch ex As Exception
Return ""
End Try
Return sb.ToString()
End Function

5) Double-click button1 & paste in this code:

Dim strMika As String = "Mika"
Dim strEncodedMika As String = EncodeHexString(strMika)
MessageBox.Show(strEncodedMika)
Dim strDecodedMika As String = DecodeHexString(strEncodedMika)
MessageBox.Show(strDecodedMika)

I hope this helps

Crouchie1998
BA (HONS) MCP MCSE
Nov 21 '05 #4
Thank You Crouchie!!! Your code was easy to understand and very useful
in my case!

--
Mika
Nov 21 '05 #5

Not sure if this is the most elegent solution but if you still need one try
this...

Dim S as String = HexAsStringToCharactersAsString("4D494B41")

S should now contain "MIKA"
Private Function HexAsStringToCharactersAsString(ByVal HexString As String)
As String

'we`re assuming HexString passed is formatted as 2 chars for each
individual Hex value
'ie A = 0A, B=0B

Dim UB As Integer = HexString.Length - 1
Dim SB As New StringBuilder

For Idx As Integer = 0 To UB Step 2
SB.Append(Microsoft.VisualBasic.ChrW(System.Conver t.ToInt32(HexString.Chars(Idx)
& HexString.Chars(Idx + 1), 16)))
Next

Return SB.ToString

End Function

"Mika M" <mahmik_nospam@removethis_luukku.com> wrote in message
news:O%****************@tk2msftngp13.phx.gbl...
Hi!

I've made little code to convert string into hex string...

Public ReadOnly Property ToHexString(ByVal text As String) As String
Get
Dim arrBytes As Integer() = CharsToBytes(text)
Dim sb As StringBuilder = New StringBuilder

For i As Integer = 0 To arrBytes.Length - 1
'// If it's a single digit, append a zero in front of it.
If (Hex(arrBytes(i)).Length = 1) Then
sb.Append("0" + Hex(arrBytes(i)))
Else
sb.Append(Hex(arrBytes(i)))
End If
Next

Return sb.ToString()
End Get
End Property

Private Function CharsToBytes(ByVal text As String) As Integer()
Dim c As Char() = text.ToCharArray()
Dim arrBytes As Integer()
ReDim arrBytes(c.Length() - 1)

For i As Integer = 0 To c.Length() - 1
arrBytes(i) = System.Convert.ToByte(c(i))
Next

Return arrBytes
End Function

... and it's working fine. For example my name "MIKA" will be "4D494B41"
as hex string, but I don't find out how to do this opposite way? I mean
how to get "MIKA" of "4D494B41" hex string.

Other question: It's possible to change when using VB like...

Asc(c(i)) -> System.Convert.ToByte(c(i))

... is there also same kind of way for Hex()-function?

--
Thanks in advance!

Mika

Nov 21 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Joel Moore | last post by:
Maybe I'm just easily baffled after an all-nighter but I can't seem to figure out how to represent a BitArray as a hexadecimal string. For example: Dim outputBank As New BitArray(8) ...
4
by: Eric Lilja | last post by:
Hello, I've made a templated class Option (a child of the abstract base class OptionBase) that stores an option name (in the form someoption=) and the value belonging to that option. The value is...
4
by: aevans1108 | last post by:
expanding this message to microsoft.public.dotnet.xml Greetings Please direct me to the right group if this is an inappropriate place to post this question. Thanks. I want to format a...
3
by: Convert TextBox.Text to Int32 Problem | last post by:
Need a little help here. I saw some related posts, so here goes... I have some textboxes which are designed for the user to enter a integer value. In "old school C" we just used the atoi function...
7
by: patang | last post by:
I want to convert amount to words. Is there any funciton available? Example: $230.30 Two Hundred Thirty Dollars and 30/100
6
by: patang | last post by:
Could someone please tell me where am I supposed to put this code. Actually my project has two forms. I created a new module and have put the following code sent by someone. All the function...
3
by: GM | last post by:
Dear all, Could you all give me some guide on how to convert my big5 string to unicode using python? I already knew that I might use cjkcodecs or python 2.4 but I still don't have idea on what...
4
by: tshad | last post by:
I am trying to convert a string character to an int where the string is all numbers. I tried: int test; string stemp = "5"; test = Convert.ToInt32(stemp); But test is equal to 53.
9
by: Marco Nef | last post by:
Hi there I'm looking for a template class that converts the template argument to a string, so something like the following should work: Convert<float>::Get() == "float"; Convert<3>::Get() ==...
0
Debadatta Mishra
by: Debadatta Mishra | last post by:
Introduction In this article I will provide you an approach to manipulate an image file. This article gives you an insight into some tricks in java so that you can conceal sensitive information...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.