using System; using System.Collections.Generic; using System.Text; namespace Be.Windows.Forms { /// /// The interface for objects that can translate between characters and bytes. /// public interface IByteCharConverter { /// /// Returns the character to display for the byte passed across. /// /// /// string ToChar(UInt64 value, out int keyLength); /// /// Returns the byte to use when the character passed across is entered during editing. /// /// /// byte ToByte(char c); byte[] GetBytes(string str); } /// /// The default implementation. /// public class DefaultByteCharConverter : IByteCharConverter { /// /// Returns the character to display for the byte passed across. /// /// /// public virtual string ToChar(UInt64 value, out int keyLength) { keyLength = 1; byte b = (byte)value; return new string(b > 0x1F && !(b > 0x7E && b < 0xA0) ? (char)b : '.', 1); } /// /// Returns the byte to use for the character passed across. /// /// /// public virtual byte ToByte(char c) { return (byte)c; } public virtual byte[] GetBytes(string str) { List bytes = new List(str.Length); foreach(char c in str) { bytes.Add((byte)c); } return bytes.ToArray(); } /// /// Returns a description of the byte char provider. /// /// public override string ToString() { return "ANSI (Default)"; } } /// /// A byte char provider that can translate bytes encoded in codepage 500 EBCDIC /// public class EbcdicByteCharProvider : IByteCharConverter { /// /// The IBM EBCDIC code page 500 encoding. Note that this is not always supported by .NET, /// the underlying platform has to provide support for it. /// private Encoding _ebcdicEncoding = Encoding.GetEncoding(500); /// /// Returns the EBCDIC character corresponding to the byte passed across. /// /// /// public virtual string ToChar(UInt64 value, out int keyLength) { keyLength = 1; byte b = (byte)value; string encoded = _ebcdicEncoding.GetString(new byte[] { b }); return new string(encoded.Length > 0 ? encoded[0] : '.', 1); } /// /// Returns the byte corresponding to the EBCDIC character passed across. /// /// /// public virtual byte ToByte(char c) { byte[] decoded = _ebcdicEncoding.GetBytes(new char[] { c }); return decoded.Length > 0 ? decoded[0] : (byte)0; } public virtual byte[] GetBytes(string str) { List bytes = new List(str.Length); foreach(char c in str) { bytes.Add((byte)c); } return bytes.ToArray(); } /// /// Returns a description of the byte char provider. /// /// public override string ToString() { return "EBCDIC (Code Page 500)"; } } }