60 lines
1.3 KiB
C#
60 lines
1.3 KiB
C#
using System;
|
|
using System.Globalization;
|
|
|
|
namespace TBF.Tools
|
|
{
|
|
public class ByteFormatter : IFormatProvider, ICustomFormatter
|
|
{
|
|
public ByteFormatter()
|
|
{
|
|
}
|
|
|
|
public object GetFormat(Type formatType)
|
|
{
|
|
if (formatType == typeof(ICustomFormatter))
|
|
return this;
|
|
else
|
|
return null;
|
|
}
|
|
|
|
public string Format(string fmt, object arg, IFormatProvider formatProvider)
|
|
{
|
|
if (arg.GetType() != typeof(byte))
|
|
{
|
|
try
|
|
{
|
|
return HandleOtherFormats(fmt, arg);
|
|
}
|
|
catch (FormatException e)
|
|
{
|
|
throw new FormatException(String.Format("The format of '{0}' is invalid.", fmt), e);
|
|
}
|
|
}
|
|
|
|
///
|
|
/// Convert one byte to string
|
|
///
|
|
byte b = (byte)arg;
|
|
if ((32 <= b) && (b <= 127)) return "'" + ((char)b).ToString() + "'";
|
|
if ((char)b == '\r') return "'\\r'";
|
|
if ((char)b == '\n') return "'\\n'";
|
|
if ((char)b == '\t') return "'\\t'";
|
|
if (b == 17) return "XON";
|
|
if (b == 19) return "XOFF";
|
|
if (b == 26) return "Ctrl-Z";
|
|
return b.ToString();
|
|
}
|
|
|
|
|
|
private string HandleOtherFormats(string format, object arg)
|
|
{
|
|
if (arg is IFormattable)
|
|
return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
|
|
else if (arg != null)
|
|
return arg.ToString();
|
|
else
|
|
return String.Empty;
|
|
}
|
|
}
|
|
}
|