Skip to content

Instantly share code, notes, and snippets.

@pisceanfoot
Created May 20, 2014 01:18
Show Gist options
  • Save pisceanfoot/8eca1c1b85c75af6edc5 to your computer and use it in GitHub Desktop.
Save pisceanfoot/8eca1c1b85c75af6edc5 to your computer and use it in GitHub Desktop.
StringConvert util
/// <summary>
/// 类名: StringConvertUtil
/// 描述: 实现字符串的转换
/// 作者: Heclei
/// 版本: 1.0.0.0
/// 日期: 2007-04-11
/// </summary>
public class StringConvert
{
#region 转16进制字符串
/// <summary>
/// Byte 数组值转16进制字符串
/// </summary>
/// <param name="b">输入参数:Byte value</param>
/// <returns>16进制字符串</returns>
public static String ByteArrayToHexString(Byte[] bytes)
{
StringBuilder temp = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
temp.Append(bytes[i].ToString("X2"));
}
return temp.ToString();
}
/// <summary>
/// Byte 值转16进制字符串
/// </summary>
/// <param name="b">输入参数:Byte value</param>
/// <returns>16进制字符串</returns>
public static String ByteToHexString(Byte b)
{
return b.ToString("X2");
}
/// <summary>
/// Converts a hex string to a byte array
/// </summary>
/// <param name="hexString">The hex string to convert</param>
/// <returns>A byte array representing the hex string</returns>
public static byte[] HexStringToByteArray(string hexString)
{
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = System.Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
#endregion
#region 获取指定长度的随机 Byte Array
/// <summary>
/// 获取指定长度的随机 Byte Array
/// </summary>
/// <param name="count">返回的Byte Array 长度</param>
/// <returns>返回指定长度的 Byte Array</returns>
public static byte[] GetRandomBytes(int count)
{
byte[] randomBytes = new byte[count];
RNGCryptoServiceProvider gen = new RNGCryptoServiceProvider();
gen.GetBytes(randomBytes);
return randomBytes;
}
#endregion
#region 日期与Byte互转
/// <summary>
/// Convert a DateTime to the equivalent long (Win32 FileTime) byte array
/// </summary>
/// <param name="date">DateTime to convert</param>
/// <returns>"long" byte array representing the DateTime</returns>
public static byte[] DateToByteArray(DateTime date)
{
long longDate = date.ToFileTime();
return BitConverter.GetBytes(longDate);
}
/// <summary>
/// Coverts a long (aka Win32 FileTime) byte array to a DateTime
/// </summary>
/// <param name="bytes">Bytes to convert</param>
/// <returns>DateTime representation of the "long" bytes</returns>
public static DateTime ByteArrayToDate(byte[] bytes)
{
if (bytes.Length != 8)
throw new ArgumentException("bytes");
long longDate = BitConverter.ToInt64(bytes, 0);
return DateTime.FromFileTime(longDate);
}
#endregion
#region IP转换
/// <summary>
/// 转换IP地址为数字
/// </summary>
/// <returns></returns>
public static int IPToInteger(string ip)
{
int ipInteger = -1;
string[] ipArray = ip.Split('.');
if (ipArray.Length == 4)
{
ipInteger = System.Convert.ToInt32(ipArray[0]) * 16777216 + System.Convert.ToInt32(ipArray[1]) * 65536 + System.Convert.ToInt32(ipArray[2]) * 256 + System.Convert.ToInt32(ipArray[3]);
}
return ipInteger;
}
/// <summary>
/// IP数字转字符
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static string IntegerIpToStr(int ip)
{
string strIp = string.Empty;
int w = ip / 16777216 % 256;
int x = ip / 65536 % 256;
int y = ip / 256 % 256;
int z = ip % 256;
strIp = string.Format("{0}.{1}.{2}.{3}", w, x, y, z);
return strIp;
}
#endregion
#region 全角数字转换为数字
/// <summary>
/// 将全角数字转换为数字
/// </summary>
/// <param name="SBCCase"></param>
/// <returns></returns>
public static string SBCCaseToNumberic(string SBCCase)
{
char[] c = SBCCase.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
if (b.Length == 2)
{
if (b[1] == 255)
{
b[0] = (byte)(b[0] + 32);
b[1] = 0;
c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
}
}
}
return new string(c);
}
#endregion
#region Size formatting functions
public static string FormatSizeBinary(Int64 size)
{
return FormatSizeBinary(size, 2);
}
public static string FormatSizeBinary(Int64 size, Int32 decimals)
{
String[] sizes = { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
Double formattedSize = size;
Int32 sizeIndex = 0;
while (formattedSize >= 1024 && sizeIndex < sizes.Length)
{
formattedSize /= 1024;
sizeIndex += 1;
}
return Math.Round(formattedSize, decimals) + sizes[sizeIndex];
}
public static string FormatSizeDecimal(Int64 size)
{
return FormatSizeDecimal(size, 2);
}
public static string FormatSizeDecimal(Int64 size, Int32 decimals)
{
String[] sizes = { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
Double formattedSize = size;
Int32 sizeIndex = 0;
while (formattedSize >= 1000 && sizeIndex < sizes.Length)
{
formattedSize /= 1000;
sizeIndex += 1;
}
return Math.Round(formattedSize, decimals) + sizes[sizeIndex];
}
#endregion
#region Data TO JSON
/// <summary>
/// 将数据表转换成JSON类型串
/// </summary>
/// <param name="dt">要转换的数据表</param>
/// <returns></returns>
public static StringBuilder DataTableToJSON(System.Data.DataTable dt)
{
return DataTableToJson(dt, true);
}
/// <summary>
/// 将数据表转换成JSON类型串
/// </summary>
/// <param name="dt">要转换的数据表</param>
/// <param name="dispose">数据表转换结束后是否dispose掉</param>
/// <returns></returns>
public static StringBuilder DataTableToJson(System.Data.DataTable dt, bool dt_dispose)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("[\r\n");
//数据表字段名和类型数组
string[] dt_field = new string[dt.Columns.Count];
int i = 0;
string formatStr = "{{";
string fieldtype = "";
foreach (System.Data.DataColumn dc in dt.Columns)
{
dt_field[i] = dc.Caption.ToLower().Trim();
formatStr += "'" + dc.Caption.ToLower().Trim() + "':";
fieldtype = dc.DataType.ToString().Trim().ToLower();
if (fieldtype.IndexOf("int") > 0 || fieldtype.IndexOf("deci") > 0 ||
fieldtype.IndexOf("floa") > 0 || fieldtype.IndexOf("doub") > 0 ||
fieldtype.IndexOf("bool") > 0)
{
formatStr += "{" + i + "}";
}
else
{
formatStr += "'{" + i + "}'";
}
formatStr += ",";
i++;
}
if (formatStr.EndsWith(","))
{
formatStr = formatStr.Substring(0, formatStr.Length - 1);//去掉尾部","号
}
formatStr += "}},";
i = 0;
object[] objectArray = new object[dt_field.Length];
foreach (System.Data.DataRow dr in dt.Rows)
{
foreach (string fieldname in dt_field)
{ //对 \ , ' 符号进行转换
objectArray[i] = dr[dt_field[i]].ToString().Trim().Replace("\\", "\\\\").Replace("'", "\\'");
switch (objectArray[i].ToString())
{
case "True":
{
objectArray[i] = "true"; break;
}
case "False":
{
objectArray[i] = "false"; break;
}
default: break;
}
i++;
}
i = 0;
stringBuilder.Append(string.Format(formatStr, objectArray));
}
if (stringBuilder.ToString().EndsWith(","))
{
stringBuilder.Remove(stringBuilder.Length - 1, 1);//去掉尾部","号
}
if (dt_dispose)
{
dt.Dispose();
}
return stringBuilder.Append("\r\n];");
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment