105 lines
3.3 KiB
C#
105 lines
3.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Globalization;
|
|
using System.Text;
|
|
|
|
namespace ET
|
|
{
|
|
public static class StringHelper
|
|
{
|
|
public static IEnumerable<byte> ToBytes(this string str)
|
|
{
|
|
byte[] byteArray = Encoding.Default.GetBytes(str);
|
|
return byteArray;
|
|
}
|
|
|
|
public static byte[] ToByteArray(this string str)
|
|
{
|
|
byte[] byteArray = Encoding.Default.GetBytes(str);
|
|
return byteArray;
|
|
}
|
|
|
|
public static byte[] ToUtf8(this string str)
|
|
{
|
|
byte[] byteArray = Encoding.UTF8.GetBytes(str);
|
|
return byteArray;
|
|
}
|
|
|
|
public static byte[] HexToBytes(this string hexString)
|
|
{
|
|
if (hexString.Length % 2 != 0)
|
|
{
|
|
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
|
|
}
|
|
|
|
byte[] hexAsBytes = new byte[hexString.Length / 2];
|
|
for (int index = 0; index < hexAsBytes.Length; index++)
|
|
{
|
|
string byteValue = "";
|
|
byteValue += hexString[index * 2];
|
|
byteValue += hexString[index * 2 + 1];
|
|
hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
|
}
|
|
return hexAsBytes;
|
|
}
|
|
|
|
public static string Fmt(this string text, params object[] args)
|
|
{
|
|
return string.Format(text, args);
|
|
}
|
|
|
|
public static string ListToString<T>(this IEnumerable<T> list)
|
|
{
|
|
StringBuilder sb = new StringBuilder();
|
|
foreach (T t in list)
|
|
{
|
|
sb.Append(t);
|
|
sb.Append(",");
|
|
}
|
|
return sb.ToString();
|
|
}
|
|
public static string ToCustomString(this object obj)
|
|
{
|
|
if (obj == null)
|
|
return string.Empty;
|
|
switch (obj)
|
|
{
|
|
default:
|
|
{
|
|
if (obj.GetType().IsGenericType)
|
|
{
|
|
StringBuilder sb = new StringBuilder();
|
|
sb.Append("[");
|
|
|
|
dynamic x = obj;
|
|
foreach (dynamic item in x)
|
|
{
|
|
sb.Append(item);
|
|
sb.Append(",");
|
|
}
|
|
sb.Remove(sb.Length - 1, 1);
|
|
sb.Append("]\n");
|
|
return sb.ToString();
|
|
}
|
|
else
|
|
return obj.ToString();
|
|
}
|
|
case Array array:
|
|
{
|
|
StringBuilder sb = new StringBuilder();
|
|
sb.Append("[");
|
|
foreach (object item in array)
|
|
{
|
|
sb.Append(item);
|
|
sb.Append(",");
|
|
}
|
|
sb.Remove(sb.Length - 1, 1);
|
|
sb.Append("]\n");
|
|
|
|
return sb.ToString();
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
} |