常用转换函数
一、Unicode和UTF8互相转化
// 转换接收到的字符串
public string UTF8ToUnicode(string recvStr)
{
byte[] tempStr = Encoding.UTF8.GetBytes(recvStr);
byte[] tempDef = Encoding.Convert(Encoding.UTF8, Encoding.Default, tempStr);
string msgBody = Encoding.Default.GetString(tempDef);
return msgBody;
}
// 转换要发送的字符数组
public byte[] UnicodeToUTF8(string sendStr)
{
byte[] msgBody = Encoding.UTF8.GetBytes(sendStr);
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;
}
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/15763892.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。