首页  编辑  

十六进制的转换

Tags: /C#/字符串处理/   Date Created:

public string StrToHex( string mStr) //

{

    return BitConverter . ToString(

        ASCIIEncoding . Default . GetBytes(mStr)) . Replace( "-" , " " );

} /* StrToHex */

public string HexToStr( string mHex) //

{

   mHex = mHex . Replace( " " , "" );

    if (mHex . Length <= 0 ) return "" ;

    byte [] vBytes = new byte [mHex . Length / 2 ];

    for ( int i = 0 ; i < mHex . Length; i += 2 )

        if ( ! byte . TryParse(mHex . Substring(i, 2 ), NumberStyles . HexNumber, null , out vBytes[i / 2 ]))

           vBytes[i / 2 ] = 0 ;

   

    return ASCIIEncoding . Default . GetString(vBytes);

} /* HexToStr */

//------------------------------

public byte [] HexToBytes( string AHex)

{

   AHex = AHex . Replace( " " , "" );

    if (AHex . Length <= 0 ) return null ;

    byte [] Result = new byte [AHex . Length / 2 ];

    for ( int i = 0 ; i < AHex . Length; i += 2 )

        if ( ! byte . TryParse(AHex . Substring(i, 2 ),

           System . Globalization . NumberStyles . HexNumber, null , out Result[i / 2 ]))

           Result[i / 2 ] = 0 ;

    return Result;

}