13
Wed, Nov
5 New Articles

Integers and RPG

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

Integers fields are a fantastic way to store relatively large numbers in a small space, but getting RPG to play nice isn't always easy.

 

There are times when RPG simply leaps forward into the future and times when it needs a little cajoling. The whole concept of ILE was a quantum leap. Integer support, a little less so.

Integer and Binary

The biggest problem is the fact that RPG has long had support for a field type similar to the integer, called a binary field. The main difference has to do with the way the maximum value is defined. For integer fields, it is the binary maximum based on the number of bytes in the field: a two-byte unsigned field can range from 0 to 65535 (the signed version goes from -32768 to 32767), and they never have decimal precision. Meanwhile, you specify binary (type B) fields with digits and precision like any other numeric field type in RPG, and in fact when the field is brought in from disk, the default is to actually represent it internally in the RPG program as a packed field. So basically, this just allows the data to be stored in fewer bytes: a decimal value that can hold up to four digits of information requires three packed decimal bytes. The same binary field takes only two bytes but at the cost of converting back and forth between packed and binary every time you access the database.

 

I won't go into a long discussion, especially since binary fields are deprecated; you really should never use them. Instead, you should always use integer fields, and in fact when you use DDL to define your files, you will see some strange throwbacks to the olden days of binary fields.

What Happens with DDL

When using DDL to create files, you don't even have the option of creating a binary field, at least not the way RPG understands. Binary fields in DDL mean something completely different: large strings of hexadecimal data.

 

Instead, if you're creating numeric binary fields in DDL, you use one of three data types: INTEGER, BIGINT, or SMALLINT. As the names imply, the primary difference between these field types is size. SMALLINT is two bytes, INTEGER is four bytes, BIGINT is eight bytes.

 

 CREATE TABLE JDPTST/BININTDDL

   (ANINT INTEGER NOT NULL WITH DEFAULT,  

    ABIGINT BIGINT NOT NULL WITH DEFAULT,

    ASMALLINT SMALLINT NOT NULL WITH DEFAULT)       

 

I then use this file in a program:

 

 h DEBUG                                     

 fbinintddl if   e           k disk   

                                 

  /free                                

   read binintddl;           

   *inlr = *on;                      

  /end-free                              

 

Note: I use DEBUG to make sure all fields are compiled, even if they're not used. Otherwise, the compiler ignores them. Also, the program as defined wouldn't compile anyway, because by default a file defined with SQL has a record format whose name is the same as the file. Either you would have to rename the format in the RPG program using the RENAME keyword on the F-spec, or you could assign the record format name using the RCDFMT keyword in the CREATE TABLE command, as outlined in a recent TechTip by Kent Milligan.

 

Anyway, if you then look at the compile listing, you would see that the fields are defined as follows:

 

 ABIGINT           P(20,0)                 7D

 ANINT             P(9,0)                  6D

 ASMALLINT         P(4,0)                  8D

 

Note first off that they are packed. This can be an issue, especially when passing data to other languages in data structures (an issue I'll address in more detail in a moment). But another issue is the size of the field. Note that SMALLINT is defined as four positions, even though it can hold values up to 32767 (or 65535 for an unsigned value). RPG limits the size to four digits, because it tries to figure out the largest number of digits that can be held with all nines. Since 9999 can fit in the SMALLINT type but 99999 cannot, RPG conservatively sets the size to four digits.

 

What happens, though, is that if you try to assign a value higher than 9999, even a value like 10000, which can easily fit in the field, RPG fails with an RNQ0103 error: target too small to hold result. To get around this problem, use the EXTBININT(*YES) keyword on the H-spec:

 

 h DEBUG EXTBININT(*YES)                                                    

 

Compiled this way, the field sizes change:

 

 ABIGINT           P(20,0)                 7D 

 ANINT             P(10,0)                 6D 

 ASMALLINT         P(5,0)                  8D 

 

Now you can actually update the fields to contain their maximum values. In fact, you have to be careful not to put values in that are too large. You can set the ASMALLINT value to 99999, but if you attempt to write or update the database with that value, you'll trigger the RNQ0103 error. Also note that the field ABIGINT doesn't change. For some reason, the conservative redefinition technique (which should have resulted in a field of 19 digits, not 20) does not apply to 64-bit numbers. They are always redefined to the appropriate maximum 20-digit field.

Communicating with Other Languages

So on to the last piece of the puzzle. Over the years, I've found the best way to pass data between languages is by using data structures. There are pluses and minuses to the technique, but in general I much prefer the idea of sending one or two data structures with predefined layouts. Please note that I am not talking about passing data between machines, especially over the Internet. In those cases, it's far easier to debug data that's sent textually, using a standard format such as XML or JavaScript Object Notation (JSON), and the amount of data passed as opposed to things like latency and so on makes saving bytes less of an issue.

 

But when I'm talking about large quantities of small packets of data, such as between layers in a multi-tiered application, I find the data structure technique to be invaluable. In general, the linkage between tiers is just a couple of buffers, and as the requirements change, I just change the conversion code, not the linkage details. Doing this can eliminate some headaches, such as hitting the maximum number of parameters.

 

Since IBM has been very good about providing support for packed decimal fields in Java (even though Java itself lags behind pretty badly), I've used packed decimal for many years. However, as more and more SQL enters the fray and integer values (record numbers, ID fields, timestamps) abound, I recently decided to start using integer numbers in my DDL and thus in my RPG programs. And this is where another legacy issue with RPG comes into play.

 

Note that even with the EXTBININT(*YES) keyword specified, my fields were being defined as packed fields. I create a message data structure like so:

 

 d message         ds                                

 d   MSG_SMALLINT                      like(ASMALLINT)

 d   MSG_INT                           like(ANINT)   

 d   MSG_BIGINT                        like(ABIGINT) 

 

And then look at the definition:

 

 MESSAGE           DS(20) 

 MSG_BIGINT        P(20,0)

 MSG_INT           P(10,0)

 MSG_SMALLINT      P(5,0) 

 

As you can see, the data structure is 20 characters long. This makes sense for packed fields; a P(20,0) field takes 11 bytes, P(10,0) takes 6, and the P(5,0) takes 3. But the program on the other side will be expecting binary data with fields of sizes 8, 4, and 2 respectively, and a total size of 14: You will get all kinds of numeric conversion errors with this setup.

 

This is because by default RPG will always convert fields from database files to packed, and we saw that in the listings. The only way around this is to force the database definitions to be honored, which you do by specifying an externally described data structure. Add this line before the message DS definition:

 

 d dsbid         e ds                  extname(BININTDDL)

 

Now the database fields will no longer be converted to packed, and you can see that in the cross-reference:

 

 ABIGINT           I(20,0)

 ANINT             I(10,0)

 ASMALLINT         I(5,0)

 

And thanks to that change, magic occurs with the LIKE defines in the message data structure as well:

 

 MESSAGE           DS(14)

 MSG_BIGINT        I(20,0)

 MSG_INT           I(10,0)

 MSG_SMALLINT      I(5,0)

 

Note that the fields are now defined as integer (type I) fields, and the data structure is now only 14 characters long, as it should be. You can now define this data structure in another language like EGL or Java using integer fields, and the two programs will communicate correctly.

 

Many thanks to Barbara Morris for patiently explaining to me the issues involved. If you remember to use both of these techniques--the EXTBININT(*YES) and the externally described data structure--you will be able to better communicate binary numeric data between your tiers.

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

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: