字符串转byte(xxx)格式字符串数组
2015-10-04 10:27:57 访问(2273) 赞(0) 踩(0)
/// <summary>
/// 字符串转成byte[]数组的String
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string StringToByteArrayString(string str)
{
if (str == null || str.Length == 0)
return "";
byte[] byteArray = Encoding.Default.GetBytes(str);
return ByteArrayToString(byteArray);
}
/// <summary>
/// 字符串转成byte[]数组的String
/// </summary>
/// <param name="str"></param>
/// <param name="_encoding"></param>
/// <returns></returns>
public static string StringToByteArrayString(string str, System.Text.Encoding _encoding)
{
if (str == null || str.Length == 0)
return "";
if (_encoding == null)
{
throw new Exception
(
"方法:"
+ MethodBase.GetCurrentMethod().ReflectedType.FullName
+ " "
+ MethodBase.GetCurrentMethod().ToString()
+ " 发生异常:"
+ "传入参数:System.Text.Encoding _encoding 为null。"
);
}
byte[] byteArray = _encoding.GetBytes(str);
return ByteArrayToString(byteArray);
}
/// <summary>
///
/// </summary>
/// <param name="byteArray"></param>
/// <returns></returns>
public static string ByteArrayToString(byte[] byteArray)
{
if (byteArray == null)
{
throw new Exception
(
"方法:"
+ MethodBase.GetCurrentMethod().ReflectedType.FullName
+ " "
+ MethodBase.GetCurrentMethod().ToString()
+ " 发生异常:"
+ "传入参数:byte[] byteArray 为null。"
);
}
StringBuilder theResult = new StringBuilder();
foreach (byte b in byteArray)
{
theResult.Append(b.ToString().PadLeft(3, '0'));
}
return theResult.ToString();
}
/// <summary>
/// 字符串转成byte[]数组
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static byte[] StringToByteArray(string str)
{
if (str == null || str.Length == 0)
return null;
int iLen = str.Length;
if (iLen % 3 != 0)
{
throw new Exception
(
"方法:"
+ MethodBase.GetCurrentMethod().ReflectedType.FullName
+ " "
+ MethodBase.GetCurrentMethod().ToString()
+ " 发生异常:"
+ "iLen % 3 != 0,传入的字符串不是合理的byte[]值。"
);
}
int iArrayLen = iLen / 3;
byte[] theResult = new byte[iArrayLen];
string strItem = string.Empty;
byte bItem = 1;
for (int i = 0; i < iArrayLen; ++i)
{
strItem = str.Substring(i * 3, 3);
bItem = byte.Parse(strItem);
theResult[i] = bItem;
}
return theResult;
}
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ByteArrayStringToString(string str)
{
byte[] bArray = StringToByteArray(str);
return Encoding.Default.GetString(bArray);
}
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <param name="_encoding"></param>
/// <returns></returns>
public static string ByteArrayStringToString
(
string str,
System.Text.Encoding _encoding
)
{
if (_encoding == null)
{
throw new Exception
(
"方法:"
+ MethodBase.GetCurrentMethod().ReflectedType.FullName
+ " "
+ MethodBase.GetCurrentMethod().ToString()
+ " 发生异常:"
+ "传入参数:System.Text.Encoding _encoding 为null。"
);
}
byte[] bArray = StringToByteArray(str);
return _encoding.GetString(bArray);
}
标签:
字符串转byte(xxx)格式字符串数组 


上一条:
下一条:
相关评论
发表评论