常用转换函数

一、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;
        }

本文来自博客园,作者:農碼一生,转载请注明原文链接: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
进开发学习交流群:

原文地址:https://www.cnblogs.com/wml-it/p/15763892.html