Written by

Question wx fg · Jul 12, 2017

Is there a function for convert string to hex?

hi

  is there a built in function for convert string to hex.  for example

"abc"   convert to "616263"

thanks

Comments

Sean Connelly · Jul 12, 2017

I don't think there is a function that will do it in one step for you.

There is the $zhex function which will convert a decimal to a hex value.

If you combine it with $ascii you can do one character at a time...

>w $zhex($ascii("a"))
61


Use a for loop and you can get the result you want...

>set hex="" for i=1:1:$l("abc") set hex=hex_$zhex($ascii($e("abc",i)))
>w hex
616263


There is also a utility which may of be of use to you when working on the command line...

>zzdump "abc"
0000: 61 62 63


Sean

0
Vitaliy Serdtsev  Jul 18, 2017 to Ed de Moel
The solution with ##class(%xsd.hexBinary).LogicalToXSD works, but be careful, it only works when all characters in the string have codes <256.
All right, because the function works with an array of bytes (binary). Therefore pre-to need lead N-byte string to single-byte string and only then do the conversion, for example:
trantable="SAME","UTF8" {
 "-------",!,trantable,!
 xN="π=3.14159..." zzdump xN !
 x1=$zcvt(xN,"O",trantablezzdump x1 !!
     
 hex=##class(%xsd.hexBinary).LogicalToXSD(x1)
 zw hex
     
 w $zcvt(##class(%xsd.hexBinary).XSDToLogical(hex),"I",trantable),!!
}

USER><FONT COLOR="#0000ff">d </FONT><FONT COLOR="#000000">^test</FONT>

SAME

0000: 03C0 003D 0033 002E 0031 0034 0031 0035 π=3.1415 0008: 0039 002E 002E 002E 9...

0000: C0 03 3D 00 33 00 2E 00 31 00 34 00 31 00 35 00 À.=.3...1.4.1.5. 0010: 39 00 2E 00 2E 00 2E 00 9.......

hex="C0033D0033002E00310034003100350039002E002E002E00" π=3.14159...


UTF8

0000: 03C0 003D 0033 002E 0031 0034 0031 0035 π=3.1415 0008: 0039 002E 002E 002E 9...

0000: CF 80 3D 33 2E 31 34 31 35 39 2E 2E 2E Ï.=3.14159...

hex="CF803D332E31343135392E2E2E" π=3.14159...

0
Aman Rana · Jul 12, 2017

You can try loop over something like below
w $ZHEX($ASCII("a"))

0
Vitaliy Serdtsev · Jul 12, 2017
USER>##class(%xsd.hexBinary).LogicalToXSD("abc")
616263
0
Ed de Moel · Jul 17, 2017

The solution with ##class(%xsd.hexBinary).LogicalToXSD works, but be careful, it only works when all characters in the string have codes <256.

For instance:

USER>w x
π=3.14159...
USER>w ##class(%xsd.hexBinary).LogicalToXSD(x)
3C03D332E31343135392E2E2E

The code for pi (π) is 960, and its hex rendition is three characters (3C0).

0