C语言url decode/encode (Linux Ubuntu环境)

u_char LOW_BYTE_MASK = 15;
char* HEXS = (char*)"0123456789ABCDEF";
char* URL_ALLOW = (char*)"abcdefghijklmnopqrstuvwxyz/:#?&=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-,._*~@!$^()[]{}';|";

#define BudaHex2Dec(c) (c<='9'? (c-'0'):(c<='Z'? (c-55):(c-87)))
#define BudaPreWrite(max_len, dec, fail) if((max_len-=dec)<0) goto fail;
#define BudaPreWrite1(max_len, fail) if((--max_len)<0) goto fail;

int url_encode(u_char *s, u_char *d, int max_len)
{
  u_char c, c_high, c_low, *ps = s, *pd=d; 
  while(c=*(ps++))
  {
    if(strchr(URL_ALLOW, c)) { BudaPreWrite1(max_len, fail); *(pd++) = c; }
    else { BudaPreWrite(max_len, 3, fail); *(pd++) = '%'; *(pd++) = HEXS[c >> 4]; *(pd++) = HEXS[c & BYTE_LOW4_MASK]; }
  }
  *pd=0;

  succeed: return 0;
  fail: log("url_encode failed"); return -1;
}

int url_decode(u_char *s, u_char *d, int max_len)
{
  u_char c, *ps=s, *pd=d, c_high, c_low;
  while(c=*(ps++))
  {
    BudaPreWrite1(max_len, fail); 
    if (c != '%') *(pd++) = c;
    else
    {
      c = *(ps++); c_high=BudaHex2Dec(c); c = *(ps++); c_low=BudaHex2Dec(c); 
      c = *(pd++) = ((c_high<<4) | c_low); //printf("decoded ");
    }
  }
  *pd=0;

  succeed: return 0;
  fail: log("url_decode failed"); return -1;
}

参考资料

RFC 3986 - Uniform Resource Identifier (URI): Generic Syntax

gemini

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qiuzen

您的资助将帮助我创作更好的作品

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值