Tuesday, April 13, 2010

Hex Encoding Characters

Does anyone have a PeopleCode algorithm for hex encoding strings? I'm working on an escapeJSON function and would like to come up with a good way to convert unsafe characters to unicode. Here is what I've come up with, but I would like to hear other ideas:

Local JavaObject &int = GetJavaClass("java.lang.Integer");
Local string &unicode;

REM ** I hard coded the source character to A for this example;
&unicode = "\u" | Right("0000" | &int.toHexString(Code("A")), 4);

This converts "A" to \u0041. The actual Hex part is


I don't think there is anything wrong with my solution. I am just wondering if I overlooked some PeopleCode function for displaying numbers in Hex.


Bauke Gehem said...

Have you considered using JSON.simple?


Jim Marion said...

@Bauke, JSON.simple is my favorite JSON library. Yes, I have considered, and do use it. I have another blog post in the works about that. I wanted to post it last night, but didn't quite get it finished.

St├ęphane Lapierre said...

have you ever considered PeopleSoft PET ?
there are several algorithm like PSHexEncode and PSHexDecode ...

Jim Marion said...

Yes, actually, I am familiar with PET. I use it Here. I'll have to look into that for this case.

jarodmerle said...

It's probably more work than what you did, but you could do something like this natively in PeopleCode without using a Java Object:

Function hexVal(&iH As integer) Returns string
If &iH <= 9 Then
Return String(&iH);
Return String(Char(Mod(&iH, 9) + 64));

Function toHex(&iV As integer) Returns string
Local integer &iH = Mod(&iV, 16);
Local string &sResult = "";

If &iV - &iH = 0 Then
&sResult = hexVal(&iH);
&sResult = toHex(Int((&iV - &iH) / 16)) | hexVal(&iH);

Return &sResult;

&sHexValue = hexVal(Code("A"));

Not super fancy, but it works. I snagged the algorithm from Wikipedia and converted it to PeopleCode.

Jim Marion said...

@jarodmerle, Well done. Thank you.

jarodmerle said...

You bet, your blog is great, so I figured it was about time I contribute even something of minimal value rather than being a total freeloader :). I have to respect fellow JJM's after all.

Jim Marion said...

@jarodmerle, :)