3

here is a script which convert string into hex code:

strString = "test"
strHex =""
For i=1 To Len(strString)
    strHex = strHex & " "  & Hex(Asc(Mid(strString,i,1)))
Next

strHex = Right(strHex,Len(strHex)-1)

WScript.Echo strHex

I want to do a reverse action which converts hex into string, is this possible using vbscript?

1 Answer 1

6

VBScript uses "&H" to mark numbers as hexadecimals. So

>> WScript.Echo Chr("&H" & "41")
>>
A
>>

demonstrates the strategy in principle. Demo code:

Option Explicit

Function s2a(s)
  ReDim a(Len(s) - 1)
  Dim i
  For i = 0 To UBound(a)
      a(i) = Mid(s, i + 1, 1)
  Next
  s2a = a
End Function

Function s2h(s)
  Dim a : a = s2a(s)
  Dim i
  For i = 0 To UBound(a)
      a(i) = Right(00 & Hex(Asc(a(i))), 2)
  Next
  s2h = Join(a)
End Function

Function h2s(h)
  Dim a : a = Split(h)
  Dim i
  For i = 0 To UBound(a)
      a(i) = Chr("&H" & a(i))
  Next
  h2s = Join(a, "")
End Function

Dim s : s = "test"
WScript.Echo 0, s
WScript.Echo 1, s2h(s)
WScript.Echo 2, h2s(s2h(s))

output:

0 test
1 74 65 73 74
2 test

Update wrt comment/unicode:

Use AscW/ChrW (VB ref) to deal with UTF 16.

Option Explicit

Function s2a(s)
  ReDim a(Len(s) - 1)
  Dim i
  For i = 0 To UBound(a)
      a(i) = Mid(s, i + 1, 1)
  Next
  s2a = a
End Function

Function s2h(s)
  Dim a : a = s2a(s)
  Dim i
  For i = 0 To UBound(a)
      a(i) = Right("0000" & Hex(AscW(a(i))), 4)
  Next
  s2h = Join(a)
End Function

Function h2s(h)
  Dim a : a = Split(h)
  Dim i
  For i = 0 To UBound(a)
      a(i) = ChrW("&H" & a(i))
  Next
  h2s = Join(a, "")
End Function

Dim s : s = "abcä" & ChrW("&H" & "d98a")
WScript.Echo 0, s
WScript.Echo 1, s2h(s)
WScript.Echo 2, h2s(s2h(s))
Sign up to request clarification or add additional context in comments.

8 Comments

But there is a problem, it can not convert unicode characters, go to this site hex.online-toolz.com/tools/text-hex-convertor.php and try to convert (d98a) from hex into string, it will work but in vbscript it is not working :(
@Stranger - please see update and mark fix of error in the ASCII version.
thanks for update, but still there is a problem, it will show unreadable characters as Unicode chars. is there any way to solve this problem?
@Stranger - please publish detailed description/representative sample of your input data.
@Stranger - can you rule out that the result just reflects the incapability of the output device (console, msgbox, ...) to display those characters? Did you compare h2s(s2h(s)) against s?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.