C# 一些常用小功能2
1、转换十六进制字符串到字节数组
将string类型的数据“01 02 AA 1B”转换成byte[]类型的数据:0x01 0x02 0xA 0x1B
/// <summary>
/// 转换十六进制字符串到字节数组
/// </summary>
/// <param name="msg">待转换字符串</param>
/// <returns>字节数组</returns>
///
public static byte[] HexToByte(this string msg)
{
msg = msg.Replace(" ", "");//移除空格
byte[] comBuffer = new byte[msg.Length / 2];
for (int i = 0; i < msg.Length; i += 2)
{
try
{
comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
}
catch (Exception ex)
{
return new byte[] { };
}
}
return comBuffer;
}
2、格式化JSON字符串
private static string ConvertJsonString(string str)
{
JsonSerializer serializer = new JsonSerializer();
TextReader tr = new StringReader(str);
JsonTextReader jtr = new JsonTextReader(tr);
object obj = serializer.Deserialize(jtr);
if (obj != null)
{
StringWriter textWriter = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
{
Formatting = Formatting.Indented,
Indentation = 4,
IndentChar = ' '
};
serializer.Serialize(jsonWriter, obj);
return textWriter.ToString();
}
else
{
return str;
}
}