C#常用功能及转换封装

1、常用函数封装:CommonFunction

class CommonFunction
{
    //字节转换为中文
    public static String GetGB2312fromByteArray(Byte[] pdata, int start, int len)
    {
        string result = "";
        try
        {
            result = Encoding.GetEncoding("GB2312").GetString(pdata, start, len);
            int pos = result.IndexOf("\0");
            if (pos >= 0 && pos < result.Length)
            {
                result = result.Substring(0, pos);
            }
    
        }
        catch (System.Exception )
        {
            result = GetStringFromByteArray(pdata, start, len);
        }
        return result;
    }
    /// 将十六进制字符转换成十六进制
    public static Int32 GetHexFromCharacter(Byte ch)
    {
        if (ch >= 'a' && ch <= 'f')
        {
            return ch - 'a' + 10;
        }
        else if (ch >= 'A' && ch <= 'F')
        {
            return ch - 'A' + 10;
        }
        else if (ch >= '0' && ch <= '9')
        {
            return ch - '0';
        }
        else
        {
            return -1;
        }
    }
    
    /// 将CHAR型转换成字节数组性,如“AB”转换成字节为AB的值
    public static void InsertCharStringIntoByteArray(Byte[] pDst,
                                                     Int32 iDstStart,
                                                     Byte[] pSrc,
                                                     Int32 iSrcStart,
                                                     Int32 iSrcLen)
    {
        if (iSrcLen % 2 != 0)
        {
            return;
        }
    
        for (Int32 i = 0; i < iSrcLen; i += 2)
        {
            Int32 prev = GetHexFromCharacter(pSrc[iSrcStart + i]);
            Int32 post = GetHexFromCharacter(pSrc[iSrcStart + i + 1]);
    
            if (prev == -1 || post == -1)
            {
                return;
            }
    
            pDst[iDstStart + i / 2] = Convert.ToByte((Byte)((Byte)prev << 4) + (Byte)post);
        }
    }
    
    /// 将十六进制转换成十六进制字符
    public static Int32 GetCharacterFromHex(Byte bHalf)
    {
        if (bHalf >= 0 && bHalf <= 9)
        {
            return bHalf + '0';
        }
        else if (bHalf >= 0x0A && bHalf <= 0x0F)
        {
            return bHalf - 10 + 'A';
        }
        else
        {
            return -1;
        }
    }
    
    /// 将字节转换成CHAR型,如字节AB转换成“AB”
    public static void InsertByteArrayIntoCharString(Byte[] pDst,
                                                     Int32 iDstStart, 
                                                     Byte[] pSrc, 
                                                     Int32 iSrcStart, 
                                                     Int32 iSrcLen)
    {
        for (Int32 i = 0; i < iSrcLen; i++)
        {
            Int32 prev = GetCharacterFromHex((Byte)((pSrc[iSrcStart + i] >> 4) & 0x0F));
            Int32 post = GetCharacterFromHex((Byte)(pSrc[iSrcStart + i] & 0x0F));
            if (prev == -1 || post == -1)
            {
                return;
            }
    
            pDst[iDstStart + 2 * i] = Convert.ToByte(prev);
            pDst[iDstStart + 2 * i + 1] = Convert.ToByte(post);
        }
    }
    
    /// 将字符串插入到字节数组中
    public static void InsertStringIntoCharString(Byte[] pDst,
                                                  Int32 iDstStart,
                                                  String Str)
    {
        Byte[] pTmp = Encoding.Default.GetBytes(Str);
        Array.Copy(pTmp, 0, pDst, iDstStart, pTmp.Length);
    }
    
    /// 从指定字节数组中提取整数
    public static UInt32 GetIntFromByteArray(Byte[] pArrayData, 
                                             Int32 iStart, 
                                             Int32 iLen)
    {
        UInt32 uiTmp = 0;
        for (Int32 i = 0; i < iLen; i++)
        {
            uiTmp = pArrayData[iStart + i] + uiTmp * 256;
        }
        return uiTmp;
    }
    
    /// 将一个字符表示的整形插入到字节数组中
    public static void InsertIntIntoByteArray(Byte[] pSrcFrame,
                                              Int32 iStart,
                                              UInt32 uiData,
                                              Int32 iLen)
    {
        for (Int32 i = 0; i < iLen; i++)
        {
            pSrcFrame[iStart++] = Convert.ToByte(uiData >> ((iLen - i - 1) * 8) & 0xFF);
        }
    }
    
    /// 将字符串插入到字节数组中
    public static void InsertStringIntoByteArray(Byte[] pDst,
                                                 Int32 iDstStart,
                                                 String Str)
    {
        if (Str.Length % 2 != 0)
        {
            return;
        }
    
        for (Int32 index = 0; index < Str.Length; )
        {
            String sTmp = null;
            sTmp += Str[index++].ToString();
            sTmp += Str[index++].ToString();
            pDst[iDstStart++] = System.Byte.Parse(sTmp, System.Globalization.NumberStyles.AllowHexSpecifier);
        }
    }
    
    /// 从指定字节数组中提取字符串(一字节对应一字符串)
    public static String GetStringFromByteArray(Byte[] pArrayData,
                                                Int32 iStart,
                                                Int32 iLen)
    {
        String sTmp = null;
        for (Int32 i = 0; i < iLen; i++)
        {
            sTmp += pArrayData[iStart + i].ToString("X2");
        }
        return sTmp;
    }
    
    /// 获取磁盘可用剩余空间
    [DllImport("coredll.dll", EntryPoint = "GetDiskFreeSpaceEx")]
    public static extern int GetDiskFreeSpaceEx(string lpRootPathName,
                                                out long lpFreeBytesAvailable,
                                                out long lpTotalNumberOfBytes,
                                                out long lpTotalNumberOfFreeBytes);
    public static long GetAvailableSizeOfDisk()
    {
        try
        {
            long lpFreeBytesAvailable, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes;
    
            GetDiskFreeSpaceEx(@"\", out lpFreeBytesAvailable, out lpTotalNumberOfBytes, out lpTotalNumberOfFreeBytes);
    
            return (long.Parse(lpFreeBytesAvailable.ToString()) / 1024);
        }
        catch (System.Exception )
        {
            return 0;
        }
    
    }
}

2、日期函数封装:DateTimeFunction

class DateTimeFunction
{
    /// 获取从1970-01-01年到现在的时间秒数
    public static UInt32 GetTimeSeconds()
    {
        DateTime dt1 = new DateTime(1970, 1, 1, 0, 0, 0);
        DateTime dt2 = DateTime.Now.ToUniversalTime();
        System.TimeSpan TS = new System.TimeSpan(dt2.Ticks - dt1.Ticks);
        return (UInt32)TS.TotalSeconds;
    }

    /// 获取从1970-01-01年到指定的时间秒数
    public static UInt32 GetTimeSeconds(DateTime dt)
    {
        DateTime dt1 = new DateTime(1970, 1, 1, 0, 0, 0);
        System.TimeSpan TS = new System.TimeSpan(dt.Ticks - dt1.Ticks);

        String strZoneTime = DateTime.Now.ToString("zzz");
        String[] str = (strZoneTime.Substring(1, 5)).Split(':');

        UInt32 seconds = (UInt32)TS.TotalSeconds;
        if (strZoneTime[0] == '+')
        {
            seconds -= (Convert.ToUInt32(str[0]) * 3600 + Convert.ToUInt32(str[1]) * 60);
        }
        else
        {
            seconds += (Convert.ToUInt32(str[0]) * 3600 + Convert.ToUInt32(str[1]) * 60);
        }
        return seconds;
    }

    /// 根据秒数获取从1970-01-01年到现在的日期
    public static String GetTimeString(UInt32 uiSeconds)
    {
        DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0);

        String strZoneTime = DateTime.Now.ToString("zzz");
        String[] str = (strZoneTime.Substring(1, 5)).Split(':');

        if (strZoneTime[0] == '+')
        {
            uiSeconds += (Convert.ToUInt32(str[0]) * 3600 + Convert.ToUInt32(str[1]) * 60);
        }
        else
        {
            uiSeconds -= (Convert.ToUInt32(str[0]) * 3600 + Convert.ToUInt32(str[1]) * 60);
        }

        return (dt.AddSeconds(uiSeconds)).ToString("yyyy-MM-dd HH:mm:ss");
    }

    /// 获取从1970-01-01年到现在的时间秒数字符串
    public static Byte[] GetTimeCharString()
    {
        UInt32 second = GetTimeSeconds();
        Byte[] tmpTime = new Byte[32];
        CommonFunction.InsertStringIntoCharString(tmpTime, 0, second.ToString("X8"));

        return tmpTime;
    }

    /// 根据秒数获取从1970-01-01年到现在的日期字符串
    public static Byte[] GetDateTimeCharString(UInt32 uiSeconds)
    {
        DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0);

        String strZoneTime = DateTime.Now.ToString("zzz");
        String[] str = (strZoneTime.Substring(1, 5)).Split(':');

        if (strZoneTime[0] == '+')
        {
            uiSeconds += (Convert.ToUInt32(str[0]) * 3600 + Convert.ToUInt32(str[1]) * 60);
        }
        else
        {
            uiSeconds -= (Convert.ToUInt32(str[0]) * 3600 + Convert.ToUInt32(str[1]) * 60);
        }

        String strDateTime = (dt.AddSeconds(uiSeconds)).ToString("yyyyMMddHHmmss");

        Byte[] pDateTime = new Byte[32];
        CommonFunction.InsertStringIntoCharString(pDateTime, 0, strDateTime);

        return pDateTime;
    }


    /// 根据秒数获取从1970-01-01年到现在的日期字节串
    public static Byte[] GetDateTimeByteArray(UInt32 uiSeconds)
    {
        DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0);

        String strZoneTime = DateTime.Now.ToString("zzz");
        String[] str = (strZoneTime.Substring(1, 5)).Split(':');

        if (strZoneTime[0] == '+')
        {
            uiSeconds += (Convert.ToUInt32(str[0]) * 3600 + Convert.ToUInt32(str[1]) * 60);
        }
        else
        {
            uiSeconds -= (Convert.ToUInt32(str[0]) * 3600 + Convert.ToUInt32(str[1]) * 60);
        }

        String strDateTime = (dt.AddSeconds(uiSeconds)).ToString("yyyyMMddHHmmss");

        Byte[] pDateTime = new Byte[32];

        CommonFunction.InsertStringIntoByteArray(pDateTime, 0, strDateTime);
        return pDateTime;
    }

    /// 两个时间比较
    public static Boolean DateTimeCompare(DateTime d1, DateTime d2)
    {
        if (d1.CompareTo(d2) >= 0)
        {
            return false;
        }
        return true;
    }
}
分类:

发表回复