Doesn't C# support EBCDIC encoding?

I'm working on a project that involves parsing Xerox Metacode print streams, encoded as variable-byte EBCDIC records. The print stream data itself is in ASCII, but the record headers and control records are in EBCDIC.

I read the records in as byte arrays. I know I can convert a byte array into an ASCII string:

Encoding ascii = Encoding.ASCII;
char[] asciiChars;
string asciiString;

record = new Byte[record_size];
count = infile.Read(record,0,record_size);
asciiChars = new char[ascii.GetCharCount(record, 0, record.Length)];
ascii.GetChars(record, 0, record.Length, asciiChars, 0);
asciiString = new string(asciiChars);

Obviously not all the code is there, but that's enough to show the technique. I need to do the same thing with records I know are in EBCDIC, yet System.Text.Encoding doesn't have EBCDIC!?

Any idea how to turn a byte array into a string, using EBCDIC encoding?

Dani AI

Generated

Short answer: EBCDIC is available in .NET as code pages (for example IBM037, IBM500) rather than a single named Encoding called "EBCDIC". On the desktop .NET Framework many of those code pages are available via Encoding.GetEncoding(codePage); on .NET Core / .NET 5+ the runtime does not expose most legacy single-byte code pages by default — you enable them by installing the System.Text.Encoding.CodePages package and registering the provider. (See the .NET encodings list and provider notes and the official CodePages package.)
System.Text.Encoding (encodings list)

Quick recipe (modern runtimes):

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // once at startup (.NET Core / .NET 5+)
Encoding ebcdic = Encoding.GetEncoding(37);                    // IBM037 = EBCDIC (US/Canada)
string header = ebcdic.GetString(headerBytes);

This keeps decoding of the EBCDIC header bytes straightforward and avoids manual char-array plumbing. (If you run on the older .NET Framework you may not need the provider registration.) See the encodings list for common EBCDIC code pages.
System.Text.Encoding (encodings list)

Troubleshooting and practical tips: 1) If GetEncoding throws a NotSupported/No-data error, register the code-pages provider or run on a runtime that exposes those code pages. 2) Confirm the printer's exact EBCDIC variant — CP037 and CP500 are common, but vendor devices sometimes use custom mappings. 3) If you cannot add the provider (or need a one-off), a byte->char lookup table (the kind pointed to) is a valid fallback. 4) Register the provider exactly once at app startup. These steps let you decode just the header/control bytes with EBCDIC while leaving the ASCII body bytes alone.

Recommended Answers

All 2 Replies

What about having a look here: ?

That'll work, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.