`
netxdiy
  • 浏览: 679134 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

用VC(MFC)实现ASP中的Server.URLEncode与URLDecode

 
阅读更多

<script type="text/javascript"><!-- google_ad_client = "pub-0241434510974184"; /* auto-http.cn 右边 ,468x60 */ google_ad_slot = "0902256228"; google_ad_width = 468; google_ad_height = 60; // --></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

今天做程序因为要用到UrlEncode和UrlDecode,所以到网上找了一下,想用个现成的。找来找去,发现郑昀老师的代码思路是最清晰的,也很和胃口,但可惜的是只有一半 —— UrlEncode(),又看了看其他人写的,都不怎么样。所以一咬牙,干脆自己动手把UrlDecode()补上了,再做成头文件,以后用起来也方便(懒人啦)。

看见还有很多人搜索,所以贴出来一份给其他懒人。

代码如下:

inline BYTE toHex(const BYTE &x)
{
return x > 9 ? x + 55: x + 48;
}
inline BYTE toByte(const BYTE &x)
{
return x > 57? x - 55: x - 48;
}
CString URLDecode(CString sIn)
{
CString sOut;
const int nLen = sIn.GetLength() + 1;
register LPBYTE pOutTmp = NULL;
LPBYTE pOutBuf = NULL;
register LPBYTE pInTmp = NULL;
LPBYTE pInBuf =(LPBYTE)sIn.GetBuffer(nLen);
//alloc out buffer
pOutBuf = (LPBYTE)sOut.GetBuffer(nLen);

if(pOutBuf)
{
pInTmp = pInBuf;
pOutTmp = pOutBuf;
// do encoding
while (*pInTmp)
{
if('%'==*pInTmp)
{
pInTmp++;
*pOutTmp++ = (toByte(*pInTmp)%16<<4) + toByte(*(pInTmp+1))%16;//高4位+低4位
pInTmp++;
}
else if('+'==*pInTmp)
*pOutTmp++ = ' ';
else
*pOutTmp++ = *pInTmp;
pInTmp++;
}
*pOutTmp = '/0';
sOut.ReleaseBuffer();
}
sIn.ReleaseBuffer();

return sOut;
}
CString URLEncode(CString sIn)
{
CString sOut;
const int nLen = sIn.GetLength() + 1;
register LPBYTE pOutTmp = NULL;
LPBYTE pOutBuf = NULL;
register LPBYTE pInTmp = NULL;
LPBYTE pInBuf =(LPBYTE)sIn.GetBuffer(nLen);
//alloc out buffer
pOutBuf = (LPBYTE)sOut.GetBuffer(nLen*3);

if(pOutBuf)
{
pInTmp = pInBuf;
pOutTmp = pOutBuf;
// do encoding
while (*pInTmp)
{
if(isalnum(*pInTmp) || '-'==*pInTmp || '_'==*pInTmp || '.'==*pInTmp)
*pOutTmp++ = *pInTmp;
else if(isspace(*pInTmp))
*pOutTmp++ = '+';
else
{
*pOutTmp++ = '%';
*pOutTmp++ = toHex(*pInTmp>>4);//高4位
*pOutTmp++ = toHex(*pInTmp%16);//低4位
}
pInTmp++;
}
*pOutTmp = '/0';
sOut.ReleaseBuffer();
}
sIn.ReleaseBuffer();

return sOut;
}

代码中用了两个内联函数,想一想,那么放着也挺好,没必要整合进去。原源代码中仅对空格做了判断,Monyer又填上了“-_.”,算是更标准了些。

把这个函数放进去后,一个小工具的主要函数便完成了,再修改修改,明天放出来。

Monyer!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics