一个简单的小工具,自己写代码时经常需要用到,故自己写了一个。
用法:在对应的栏目输入即可,自动识别并转换
源码:
以float为例,float转Byte[]
private void TextBox_Float_TextChanged(object sender, TextChangedEventArgs e)
{
if (((TextBox)sender).IsFocused == false) return;
if (TextBox_Float.Text == "" || TextBox_Float.Text == null)
{
TextBox_Output.Text = "";
return;
}
try
{
float value = Convert.ToSingle(TextBox_Float.Text);
TextBox_Output.Text = toHexString(value);
}
catch (Exception)
{
return;
}
}
/// <summary>
/// 其他类型转十六进制空格分隔字符串
/// </summary>
public static string toHexString(float value)
{
string hexStr = "";
byte[] temp = BitConverter.GetBytes(value);
for (int i = 0; i < temp.Length; i++)
{
hexStr += temp[i].ToString("X2") + " ";
}
return hexStr;
}
byte[]转float
private void TextBox_Output_TextChanged(object sender, TextChangedEventArgs e)
{
if (((TextBox)sender).IsFocused == false) return;
if (TextBox_Output.Text == "" || TextBox_Output.Text == null)
{
TextBox_Float.Text = "";
return;
}
TextBox_Float.Text = GetFloat(((TextBox)sender).Text);
}
/// <summary>
/// 十六进制空格分隔字符串 转 Float
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static float GetFloat(string hexString)
{
byte[] data = HexStrToByte(hexString);
return BitConverter.ToSingle(data, 0);
}
/// <summary>
/// 将16进制的字符串转为byte[]
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] HexStrToByte(string hexString)
{
if (hexString[hexString.Length-1] == ' ')
hexString =hexString.Remove(hexString.Length-1);
string[] datastr = hexString.Split(' ');
byte[] data = new byte[datastr.Length];
for (int i = 0; i < datastr.Length; i++)
{
data[i] = Convert.ToByte(datastr[i], 16);
}
return data;
}
源码Github下载链接:https://github.com/Talonshaw/GetHexStrng.git