一、Unicode和UTF8互相转化
// 转换接收到的字符串
public string UTF8ToUnicode(string recvStr)
{
byte[] tempStr = Encoding.UTF8.GetBytes(recvNotify);
byte[] tempDef = Encoding.Convert(Encoding.UTF8, Encoding.Default, tempStr);
string msgBody = Encoding.Default.GetString(tempDef);
return msgBody;
}
// 转换要发送的字符数组
public byte[] UnicodeToUTF8(string sendStr)
{
string tempStr = Encoding.UTF8.GetString(sendStr);
byte[] msgBody = Encoding.UTF8.GetBytes(tempUTF8);
return msgBody;
}
二、其他类型互相转化
private DateTime LongToDateTime(uint times)
{
long _times =(long)times + 28800;
DateTime ds = new DateTime(1970, 1, 1, 0, 0, 0,DateTimeKind.Unspecified).AddSeconds(_times);
return ds;
}
private byte [] StructToBytes(Object structobj , int size)
{
byte []tempBytes = new byte [size];
IntPtr strcutIntptr = Marshal.AllocHGlobal(size);
//将结构体拷贝到内存中
Marshal.StructureToPtr(structobj, strcutIntptr, false);
//从内存空间拷贝到byte数组中
Marshal.Copy(strcutIntptr, tempBytes, 0, size);
Marshal.FreeHGlobal(strcutIntptr);
return tempBytes;
}
private object BytesToStruct(byte[] bytes ,Type _type)
{
int _size = Marshal.SizeOf(_type);
IntPtr structInnptr = Marshal.AllocHGlobal(_size);
Marshal.Copy(bytes, 0, structInnptr, _size);
object obj = Marshal.PtrToStructure(structInnptr, _type);
Marshal.FreeHGlobal(structInnptr);
return obj;
}
private byte [] IntptrToBytes (IntPtr tempIntptr ,int _size)
{
byte[] tempBytes = new byte[_size];
//从内存空间拷贝到byte数组中
Marshal.Copy(tempIntptr, tempBytes, 0, _size);
return tempBytes;
}
private IntPtr BytesToInptr(byte[] bytes, Type _type)
{
int _size = Marshal.SizeOf(_type);
IntPtr structInnptr = Marshal.AllocHGlobal(_size);
Marshal.Copy(bytes, 0, structInnptr, _size);
return structInnptr;
}