【VS2019 C#】各种数据类型转化
byte[] 转 string
byte[] buf = new byte[4];
string ret = System.Text.ASCIIEncoding.Default.GetString(buf);
或者简单点:
char TheCh = (char)buf[i];
string ret = TheCh;
2.string 转 byte[]
string sendValue;
byte[] array = System.Text.ASCIIEncoding.Default.GetBytes(sendValue);
3.u32 装 string
string u32_to_string(UInt32 data)
{
byte[] buf = new byte[4];
buf[0] = (byte)data;
buf[1] = (byte)(data >> 8);
buf[2] = (byte)(data >> 16);
buf[3] = (byte)(data >> 24);
string ret = System.Text.ASCIIEncoding.Default.GetString(buf);
return ret;
}
4.string转换成int型
int intA = 0;
1.intA =int.Parse(str);
2.int.TryParse(str, out intA);
3.intA = Convert.ToInt32(str);
C# int与string转化
1、int—>string
1 int a = 15;
2 string s1 = a.ToString();
3 string s2 = Convert.ToString(a);
2、string —>int
1 string s = "18";
2 int a1 = int.Parse(s);
3 int a2;
4 int.TryParse(s, out a2);
5 int a3 = Convert.ToInt32(s);
c# double转string保留两位小数
double tmp = 3.11415;
string s = tmp.toString(“f2”); 这样就是保留两位小数
把内存二进制数据转为double int 等
当用C#写上位机时,经常要与下位机通信,通信协议传来的数据都是byte[] 类型的二进制数据,C语言中,可以很简单地用memcpy来强制转换成相关数据,C#中就没这么方便,可以这样写,如下:
int Acceleration_Max_speed = BitConverter.ToInt32(buf, 0);
double Acceleration_acc_Max = BitConverter.ToDouble(buf, 8);
double Acceleration_Max_rpm = BitConverter.ToDouble(buf, 16);
还没有评论,来说两句吧...