Easy Conversion To ASCII
September 29, 2015 Ted Holt
The system we love so well has a long love affair with the EBCDIC collating sequence, but most of the world runs on ASCII and Unicode. Dealing with ASCII data has not been a trivial experience for RPG programmers, but IBM i 7.2 adds a feature that helps immensely.
In ancient days, RPG programmers would call the QDCXLATE API, which uses a translation table, to convert EBCDIC to ASCII. This is probably not a good solution. IBM’s translation tables were good for their time, but times have changed.
A modern solution is the iconv family of code conversion APIs, which use CCSIDs to convert data from one character set to another. These APIs do a great job, but to make them any more complicated we’d have to get the government involved.
On a recent project I discovered a new way to convert data from one character set to another. As of 7.2, RPG allows you to specify the CCSID of alphanumeric (character) variables. This makes data conversion a snap. Here’s an example.
dcl-s DataToConvert char(5); dcl-s AsciiData char(5) ccsid(819); DataToConvert = '0 1 2'; AsciiData = DataToConvert;
Here are the values in hexadecimal.
Is that fine, or what?!
But that’s not the way we’ve been using QDCXLATE and iconv all these years. We’ve been using those APIs to put ASCII data into EBCDIC variables. I hate that sort of thing because it’s the programming equivalent of a bald-faced lie. However, I have had to stuff ASCII into EBCDIC variables on more than one occasion in order to communicate properly with the outside world, and it will probably happen again.
In that case, use a data structure, like this:
dcl-s DataToConvert char(5); dcl-ds ConversionStructure; EBCDICData char(5) pos(1); ASCIIData char(5) ccsid(819) pos(1); end-ds; DataToConvert = '0 1 2'; AsciiData = DataToConvert; // Do something with EBCDICData
When this code runs, EBCDICData has the hexadecimal value 30 20 31 20 32, as one might expect.
Here’s a fabulous technique that may reduce or eliminate the need to lie. If your RPG program needs to pass data to another program in ASCII format, specify the appropriate CCSID in the procedure prototype.
dcl-pr SomePgm extpgm('SOMEPGM'); Data char(5) ccsid(819) const; end-pr; SomePgm (DataToConvert);
The system courteously converts the data to the ASCII format that SOMEPGM requires.
I’ve said good-bye to many old features of RPG and I don’t miss them. Now that I can specify the CCSID of character variables, I hope to say good-bye to QDCXLATE and iconv as well.