How To Convert from a .NET Int32 to EBCDIC Signed Integer

By Tony - Last updated: Friday, September 11, 2009 - Save & Share - Leave a Comment

Many of us have had to write data exports from our PC based management systems that are in some strange formats. Signed Integers (which smells of COBOL and EBCDIC on a main frame) are no exception.

Now I know all you Computer and Mini Computer (mid range) guys out there are like ‘strange format’? YOUR STRANGE TONY!!! . well maybe :)

Anyway here is my C# method for converting from System.Int32 to a signed integer string.

public static string GetSignedInt(int i)

{

    if (i == 0)

        return "0";

 

    char[] c = i.ToString().ToCharArray();

    Encoder enc = System.Text.Encoding.GetEncoding(37).GetEncoder();

    byte[] b = new byte[1];

    int usedChars;

    int usedBytes;

    bool completed;

    enc.Convert(c, c.Length – 1, 1, b, 0, 1, true, out usedChars, out usedBytes, out completed);

    if (i > 0)

        b[0] = (byte)(b[0] – 48);

    else

        b[0] = (byte)(b[0] – 32);

    c[c.Length - 1] = (char)b[0];

    Decoder dec = System.Text.Encoding.GetEncoding(37).GetDecoder();

    dec.Convert(b, 0, 1, c, c.Length – 1, 1, true, out usedBytes, out usedChars, out completed);

    return new string(c);

}

Basically I’m converting to EBCDIC first, then do the simple math that offsets us into either a positive number or negative number, then convert back to ASCII. It might be expensive to do it this way, but I’d rather it cost more if there is one less logic tree to debug :)

Posted in .NET Programming, ERP • • Top Of Page

Write a comment

You need to login to post comments!