05
Tue, Nov
5 New Articles

Character Conversion APIs

APIs
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

If you search the 'net for ways to uppercase character data, you can find some really bad methods. But here's a really good one.

 

Over the years, I have lost count of the number of times I have seen this question posed: "How do I uppercase character data?" And while the responses that I see on the Internet are getting better, I continue to see suggested "solutions" like the horrible "set the second bit on for each byte found in the range of a to z" (as shown in Figure 1) or the minimally correct "use the RPG %xlate function" (as shown in Figure 2). This first "solution" appears to work in a very restricted environment but has side effects, due to the EBCDIC collating sequence, that are not obvious. For instance, replace the value "Some character data" for variable CharData with the string "Some currency data like €100" and you will find that the Euro symbol € is "uppercased" to a symbol such as ÿ. Probably not the desired answer! The second "solution," though avoiding side effects such as the Euro being incorrectly "capitalized," does not support the full range of lowercase alphabetic characters (more on this a bit later).

 

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++

dCharData         s             50    inz('Some character data')

dCurChar          s              1                              

dIndex            s             10i 0                          

CL0N01Factor1+++++++Opcode&ExtFactor2+++++++Result++++++++Len++D+HiLoEq

 /free                                                

                                                       

  for Index = 1 to %len(%trimr(CharData));            

      CurChar = %subst(CharData :Index :1);           

      if ((CurChar >= 'a') and (CurChar <= 'z'));     

          %subst(CharData :Index :1) =                

             %bitor(CurChar :x'40');                  

      endif;                                          

  endfor;         

                                   

  dsply CharData;

  *inlr = *on;    

  return;         

 /end-free                                               

Figure 1: You can uppercase character data by setting the second bit of each byte in the range of a to z.

 

The correct answer to the question is to use the Convert Case APIs that are provided with i5/OS.

 

What follows is an extract from chapter 9, Character Conversion APIs, of my book IBM System i APIs at Work, Second Edition. This is an extraction as the actual chapter is 19 pages in length. The only change from what is found in the book is the renumbering of the referenced tables and figures. If you find this discussion of character data and CCSIDs to be of interest, you may also want to review other parts of the book. For instance chapter 14, Integrated File System APIs, discusses how UNIX-type APIs such as Read Directory Entry (readdir) may not return all files actually in a directory depending on the characters used in the file name. Of course chapter 14 also tells you what API to use in order to get around this consideration of the industry-standard readdir API. As businesses expand into the world market, proper support for the native languages of users becomes critical. The time to prepare your applications for the global marketplace is now.

 

Character data (such as names, addresses, and descriptions) most likely represents a significant amount of the data you store on the System i. Often, this character data is stored and simply retrieved for display and print purposes, but you might also need to process this character data within an application.

 

One possible form of processing character data is to convert stored mixed-case names ("ABC Company") to uppercase ("ABC COMPANY") for search purposes. This is useful when you want data values such as "Company," "COMPANY," and "COmpAny" to be treated as equivalent. For this type of processing, the system provides Convert Case APIs. The Convert Case function is provided as both a program API (QLGCNVCS) and a procedure API (QlgConvertCase) within a service program. This article starts with an example that uses the QlgConvertCase API to monocase (convert to either all uppercase or all lowercase) character data.

Monocasing Character Data Using the Convert Case API

The Convert Case API, QlgConvertCase, allows you to easily convert data from mixed case to either all uppercase or all lowercase. Now, you might be wondering at this point why you would want to use an API when RPG provides built-in functions such as %xlate for uppercasing, as shown in Figure 2.

 

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++

dUpper            c                   'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

dLower            c                   'abcdefghijklmnopqrstuvwxyz'

dText             s             20    

CL0N01Factor1+++++++Opcode&ExtFactor2+++++++Result++++++++Len++D+HiLoEq

 /free

Text = %xlate( Lower :Upper :'Beckie');

 /end-free 

Figure 2: You can also use RPG's %xlate to uppercase character data.

 

After the %xlate built-in runs, the variable Text is set to 'BECKIE', which certainly looks like an easy way to uppercase data. But what if the input string, rather than having the value 'Beckie', has the value 'Adélaïde'. After the %xlate built-in runs, the variable Text is now 'ADéLAïDE' rather than the correct 'ADÉLAÏDE'. The obvious solution is to add the constants é  and ï to lower and the corresponding É and Ï to upper (along with quite a few other Latin characters), but you will find this still isn't quite right. The reason is that the character é can only be represented in your RPG source code as one hexadecimal value. In the case of CCSID 37 (for simplicity, think of this as North American English), this would be x'51'. If your program was running in the United States, you would probably be OK. But what if your program was running in France with a CCSID of 297 (French) where the é is x'C0' and x'51' is the curly-bracket character ({)? Your program would convert a string such as '{aéiou}' to 'ÉAéIOUÈ', which is decidedly incorrect.

 

To solve this, you could create additional versions of the lower and upper constants for each Latin-1 language environment your program might run in (such as English, French, German, and Spanish). This becomes unwieldy very quickly, however. And when your program needs to run (unchanged) in an environment that doesn't use Latin-1, such as Greek or Cyrillic, it becomes extremely awkward. Is there a solution to this dilemma? Of course there is! Use the Convert Case API. This API allows you to pass in a character string, and the CCSID the character string is encoded in. The API then returns the correctly cased string.

 

The table below shows the parameters for the Convert Case API. The first parameter, Request Control Block, defines what type of case conversion you want performed. Figure 3 shows the layout of the Request Control Block when using a CCSID-based conversion.

 

The Convert Case API, Olgcvtcs or QlgConvertCase

Parameter

Description

Type

Size

1

Request Control Block

Input

Char(*)

2

Input Data

Input

Char(*)

3

Output Data

Output

Char(*)

4

Length of Data

Input

Binary(4)

5

Error Code

In/Out

Char(*)

 

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++

D*****************************************************************

D*Structure for CCSID based request                               

D*****************************************************************

DQLGIDRCB00       DS                                              

D*                                             Qlg CCSID ReqCtlBlk

D QLGTOR02                1      4B 0                             

D*                                             Type of Request    

D QLGIDOID00              5      8B 0                             

D*                                             CCSID of Input Data

D QLGCR00                 9     12B 0                              

D*                                             Case Request       

D QLGERVED04             13     22                                

D*                                             Reserved           

Figure 3: This is the qsysinc QLG member when using a CCSID-based conversion.

 

Type of Request (qlgtor02) can be one of several options: Type 1 indicates a CCSID-based request, type 2 is table-object based, and type 3 is user-defined. Our example uses type 1.

 

The CCSID of Input Data (qlgidoid00) identifies how the character data is represented or encoded. This can be a specific CCSID, such as 37 for EBCDIC North American English, 297 for EBCDIC French, 1252 for Windows Latin-1, or 1208 for UTF-8. You can also use the special value of zero to have the API use the current job CCSID, which is generally the value you will want. If you are interested in using specific CCSID values (and there are hundreds of them), the i5/OS Information Center lists the CCSIDs supported by the system. This list can be found by looking under "Programming" and then choosing "Globalization."

 

Case Request (qlgcr00) specifies the type of case conversion to be performed. The supported values are 0 (to convert the input data to uppercase) and 1 (to convert the input data to lowercase). Reserved (qlgerved04) is simply reserved space in the request control block. As is usual for APIs, this reserved field must be set to x'00's.

 

Figure 4 shows how to use the QlgConvertCase API. First, the program sets the Error Code Bytes Provided field (qusbprv) to 0 so exceptions are sent to the program. After this, the program initializes the entire request control block (qlgidrcb00) to x'00's. As mentioned in earlier chapters, this is done so we don't reference the actual reserved field, qlgerved04, in the program. Qlgerved04, being reserved, may be renamed or redefined in future releases as new functionality is added to the API. Therefore, we don't want to explicitly reference this field within the application program. After initializing qlgidrcb00 to x'00's, the program sets the specific fields that control the conversion. The program sets the conversion type (qlgtor02) to 1 (CCSID based), the CCSID (qlgidoid00) to 0 (the job CCSID is to be used), and the case request (qlgcr00) to 0 (uppercase).

 

h dftactgrp(*no)

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++

d/copy qsysinc/qrpglesrc,qlg                                   

d/copy qsysinc/qrpglesrc,qusec                                  

                                                               

dConvertCase      pr                  extproc('QlgConvertCase')

d Request                    65535    const options(*varsize)  

d InputData                  65535    const options(*varsize)  

d OutputData                     1    options(*varsize)        

d InputDataLen                  10i 0 const                    

d QUSEC                               likeds(QUSEC)            

                                                                

dInputData        s             40    inz('Some mixed TeXt')   

dOutputData       s             40                             

dWait             s              1

                             

CL0N01Factor1+++++++Opcode&ExtFactor2+++++++Result++++++++Len++D+HiLoEq

 /free                                                         

  QUSBPRV = 0;                   // use exceptions for errors  

  QLGIDRCB00 = *loval;           // set input structure to x'00'

  QLGTOR02 = 1;                  // use CCSID for monocasing   

  QLGIDOID00 = 0;                // use the job CCSID          

  QLGCR00 = 0;                   // convert to uppercase       

  ConvertCase( QLGIDRCB00 :InputData :OutputData               

              :%len(%trimr(InputData)) :QUSEC);                

  dsply OutputData;                                            

  QLGCR00 = 1;                   // convert to lowercase       

  ConvertCase( QLGIDRCB00 :OutputData :InputData               

              :%len(%trimr(OutputData)) :QUSEC);               

  dsply InputData;                                             

  *inlr = *on;                                                 

  return;                                                      

 /end-free                                                      

 

Figure 4: Convert to uppercase and lowercase using a CCSID-based conversion request.

 

QlgConvertCase is then called with an InputData parameter of 'Some mixed TeXt'. The result 'SOME MIXED TEXT' is displayed.

 

To lowercase the string, the program simply sets the case request to 1 (lowercase) and calls QlgConvertCase again, this time reversing the Input and Output parameters. The second display shows 'some mixed text'.

 

The correct uppercasing of strings such as 'Adélaïde' and '{aéiou}' can now be done automatically by simply running the program in a job having the correct job CCSID. In the United States, this would most likely be 37; in France, 297. If this program were to be run in a job CCSID of 37, but it knew that the data was really encoded in 297, then by setting qlgidoid00 to 297 rather than 0, the program would again correctly case the input data. The same is true for other language environments, such as Greek or Cyrillic. As more businesses move into a global marketplace, APIs such as Convert Case are clearly becoming more important for programmer productivity (and for the correct handling of national language data).

Bruce Vining

Bruce Vining is president and co-founder of Bruce Vining Services, LLC, a firm providing contract programming and consulting services to the System i community. He began his career in 1979 as an IBM Systems Engineer in St. Louis, Missouri, and then transferred to Rochester, Minnesota, in 1985, where he continues to reside. From 1992 until leaving IBM in 2007, Bruce was a member of the System Design Control Group responsible for OS/400 and i5/OS areas such as System APIs, Globalization, and Software Serviceability. He is also the designer of Control Language for Files (CLF).A frequent speaker and writer, Bruce can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it.. 


MC Press books written by Bruce Vining available now on the MC Press Bookstore.

IBM System i APIs at Work IBM System i APIs at Work
Leverage the power of APIs with this definitive resource.
List Price $89.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: