随锐旗下互动传媒:

字符串和十六进制之间的转换方法

http://www.weaseek.com  2008-08-14 09:59:50  来源:中国IT实验室

本文介绍了字符串和十六进制之间的转换方法。

1.C#中的代码

/// <summary>

/// <函数:Encode>

/// 作用:将字符串内容转化为16进制数据编码,其逆过程是Decode

/// 参数说明:

/// strEncode 需要转化的原始字符串

/// 转换的过程是直接把字符转换成Unicode字符,比如数字"3"-->0033,汉字"我"-->U+6211

/// 函数decode的过程是encode的逆过程.

/// </summary>

/// <param name="strEncode"></param>

/// <returns></returns>

public static string Encode(string strEncode)

{

string strReturn = "";// 存储转换后的编码

foreach (short shortx in strEncode.ToCharArray())

{

strReturn += shortx.ToString("X4");

}

return strReturn;

}

/// <summary>

/// <函数:Decode>

///作用:将16进制数据编码转化为字符串,是Encode的逆过程

/// </summary>

/// <param name="strDecode"></param>

/// <returns></returns>

public static string Decode(string strDecode)

{

string sResult = "";

for (int i = 0; i < strDecode.Length / 4; i++)

{

sResult += (char)short.Parse(strDecode.Substring(i * 4, 4), global::System.Globalization.NumberStyles.HexNumber);

}

return sResult;

}

2.VB6中的代码

'<函数:Encode>

'作用:将字符串内容转化为16进制数据编码,其逆过程是Decode

'参数说明:

'strSource 需要转化的原始字符串

Public Function Encode(strEncode As String) As String

Dim i As Long

Dim chrTmp$

Dim ByteLower$, ByteUpper$

Dim strReturn$ '存储转换后的编码

For i = 1 To Len(strEncode)

chrTmp$ = Mid(strEncode, i, 1)

ByteLower$ = Hex$(AscB(MidB$(chrTmp$, 1, 1)))

If Len(ByteLower$) = 1 Then ByteLower$ = "0" & ByteLower$

ByteUpper$ = Hex$(AscB(MidB$(chrTmp$, 2, 1)))

If Len(ByteUpper$) = 1 Then ByteUpper$ = "0" & ByteUpper$

strReturn$ = strReturn$ & ByteUpper$ & ByteLower$

Next

Encode = strReturn$

End Function

'</函数:Encode>

'<函数:Decode>

'作用:将16进制数据编码转化为字符串,是Encode的逆过程

Public Function Decode(strDecode As String) As String

Dim i As Long

Dim strCode$ '存储转换后的编码

Dim chrTmp$

On Error GoTo ErrProc

If Len(strDecode) Mod 4 <> 0 Then GoTo ErrProc

For i = 1 To Len(strDecode) Step 4

strCode = Mid$(strDecode, i, 4)

chrTmp$ = ChrW("&H" & strCode)

If chrTmp$ = "?" Then If strCode <> "003F" Then GoTo ErrProc

Decode = Decode & chrTmp$

Next

Exit Function

ErrProc:

Decode = strDecode

DealwithEvents "不能解析的消息:" & strDecode

End Function

'</函数:Decode>

[责任编辑:梧桐]热门关键词: 字符串 十六进制 C#