How can I convert an EBCDIC encoded file with PIC S9(04) COMP. to an integer value?
This file contains 1234 in the first line and -1234 on the second line.
Binary:
0101100011010010101100000101000011101111011000001011000001010000
Example:
How can I convert an EBCDIC encoded file with PIC S9(04) COMP. to an integer value?
This file contains 1234 in the first line and -1234 on the second line.
Binary:
0101100011010010101100000101000011101111011000001011000001010000
Example:
How can I convert an EBCDIC encoded file with PIC S9(04) COMP. to an integer value?
Don't do that.
During file conversion, the binary data is converted using an EBCDIC to ASCII table. The 04 D2
(+1234
) was converted to 1A 4B
. The 04
(EBCDIC SEL) was changed to 1A
(ASCII SUB), because there is no equivalent for the conversion. The D2
(EBCDIC 'K') was changed to 4B
(ASCII 'K'). There is no way to reverse the conversion, due to the SUB. The same problem exists with the conversion of -1234
.
Your best bet is to use PIC +9(04)
, which will be +1234
or -1234
both before and after conversion.
Test data using PIC +9(04)
written to file
+1234
-1234
+0001
-0001
+0000
Test program
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string path = "z:e1.txt";
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
String s = sr.ReadLine();
short n = Int16.Parse(s);
Console.WriteLine(n);
}
}
}
}
}
Displayed result
1234
-1234
1
-1
0
COBOL data types with computational usage (COMP
, COMP-n
) are not text, so you must not do any character conversion operation with them.
Computational types are stored as either binary numbers, floating point numbers, or packed decimal numbers. COMP
is binary. The length depends on the number of 9s in the PIC
clause. Note that the binary types are storeed in big-endian format.
In your case, the PIC +9(4)
occupies two bytes, each. For example. if you see
0x1234
as the hexadecimal represetation of a PIC +9(4) COMP
field in the input data, this is representing the number (0x12 * 0x100) + 0x34, in decimal (18 * 256) + 52 = 4608 + 52 = 4660.
In summary, mixed data (records) containing fields of types PIC ... USAGE DISPLAY
and PIC ... USAGE COMP-n
must never be translated, but must be split into indidual fields, and each field must be handled according to its USAGE
type.