C#常用数据转换
不多说上代码,用于个人备忘,仅供参考。
//int转byte[]
public static byte[] IntToBytes(int val)
{
byte[] res = new byte[4];
res[0] = (byte)(val >> 0);
res[1] = (byte)(val >> 8);
res[2] = (byte)(val >> 16);
res[3] = (byte)(val >> 24);
return res;
}
//int转byte[]
public static byte[] IntToBytes1(int val)
{
return BitConverter.GetBytes(val);
}
//byte[]转int
public static int BytesToInt(byte[] bytes)
{
int res = (bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24));
return res;
}
//byte[]转int
public static int BytesToInt1(byte[] bytes)
{
return BitConverter.ToInt32(bytes);
}
//字符串转byte[]
public static byte[] StringToBytes(string str)
{
return Encoding.Default.GetBytes(str);
}
//byte[]转字符串
public static string BytesToString(byte[] bytes)
{
return Encoding.Default.GetString(bytes);
}
//double转int —— 只取整数,不做四舍五入
public static int DoubleToInt(double val)
{
return (int)val;
}
//double转int —— 四舍五入
public static int DoubleToInt1(double val)
{
return Convert.ToInt32(val);
}
//int转double
public static double IntToDouble(int val)
{
return Convert.ToDouble(val);
}
//字符串转int
public static int StringToInt(string str)
{
return Convert.ToInt32(str);
}
//字符串转int
public static int StringToInt1(string str)
{
return int.Parse(str);
}
//int转字符串
public static string IntToString(int val)
{
return val.ToString();
}
//int转字符串
public static string IntToString1(int val)
{
return Convert.ToString(val);
}
//int转字符串
public static string IntToString2(int val)
{
return string.Format("{0}", val);
}
//struct转byte[]
public static byte[] StructToBytes(object structObj)
{
int size = Marshal.SizeOf(structObj);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structObj, buffer, false);
byte[] bytes = new byte[size];
Marshal.Copy(buffer, bytes, 0, size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
//byte[]转struct
public static object BytesToStruct(byte[] bytes, Type type)
{
int size = Marshal.SizeOf(type);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0, buffer, size);
return Marshal.PtrToStructure(buffer, type);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
更加详细的请自行到微软官网参考
Convert类 和 Byte.Parse 方法等