//http服务器的url解码过程
CString Decode( const CString& str, BOOL bQuery )
{
int ndx;
CString strDecoded = str;
// special processing or query strings....
if ( bQuery )
{
// change all '+' to ' '....
while( (ndx=strDecoded.Find('+')) != -1 )
strDecoded = strDecoded.Left(ndx) + ' ' + strDecoded.Mid(ndx+1);
} // first see if there are any %s to decode....
if ( strDecoded.Find( '%' ) != -1 )
{
// iterate through the string, changing %dd to special char....
for( ndx=0; ndx < strDecoded.GetLength(); ndx++ )
{
char ch = strDecoded.GetAt( ndx );
if ( ch == '%' )
{
if ( strDecoded.GetAt( ndx+1 ) == '%' )
{
// wanna keep one percent sign....
strDecoded = strDecoded.Left(ndx) + strDecoded.Mid(ndx+1);
}
else
{
// assume we have a hex value....
char ch1 = strDecoded.GetAt(ndx+1);
char ch2 = strDecoded.GetAt(ndx+2);
ch1 = ch1 >= 'A' ? (ch1&0xdf)-'A' : ch1-'0';
ch2 = ch2 >= 'A' ? (ch2&0xdf)-'A' : ch2-'0';
// replace the escape sequence with the char....
strDecoded = strDecoded.Left(ndx)
+ (char)(ch1*16 + ch2)
+ strDecoded.Mid( ndx+3 );
}
}
}
}
return strDecoded;
}//测试函数,调用上面的解码函数
void CTestHexDlg::OnDecode() 
{ CString strDecode="http://www.abc%BA%FA.com";//%BA%FA是“胡”的十六进制表示法
strDecode=Decode(strDecode,false);//返回的strDecode为"http://www.abc|p.com"
}但我不明白诸如:ch1 = ch1 >= 'A' ? (ch1&0xdf)-'A' : ch1-'0';这样的语句到底有什么用。是什么意思。具体问题如下:1. 0xdf是什么意思?为什么ch1要等于后面的表达式?
2. ch1*16是什么意思?为什么要这么做?
3. 还有,这个函数是不是url的解码过程?如果我把字符串str="http://www.abc%BA%FA.com"传递给Decode函数,Decode函数返回的字符串是"http://www.abc|p.com"?而不是预期的"http://www.abc胡.com"?(因为%BA%FA是“胡”的十六进制表示法),这是为什么?

解决方案 »

  1.   

    1. 0xdf是什么意思?为什么ch1要等于后面的表达式?
    &0xdf表示只用后7个字节
    有可能为数字如0xB5
    2. ch1*16是什么意思?为什么要这么做?
    *16因为是十六进制
      

  2.   

    ch1 = ch1 >= 'A' ? (ch1&0xdf)-'A' : ch1-'0';
    ----------------------------------------------
    取16进制字符值1) 0xdf 是 数字啊,用16进制表示有
    2) ch1*16相当于左移4位,这个是十六进制的高4位 不如 (ch1<<4)来得高效
    3) 没有解正确,说明一面的代码有问题
      

  3.   

    1. 0xdf是什么意思?为什么ch1要等于后面的表达式?
    &0xdf表示只用后7个字节
    有可能为数字如0xB5
    2. ch1*16是什么意思?为什么要这么做?
    *16因为是十六进制
      

  4.   

    要加上10
    ch1 = ch1 >= 'A' ? (ch1&0xdf)-'A'+10 : ch1-'0';
    ch2 = ch2 >= 'A' ? (ch2&0xdf)-'A'+10 : ch2-'0';