URLエンコード(Percent-Encoding)をデコードする方法は単純な処理なので実装するのは簡単なのですが、いざ欲しいと思うと何故かOSには用意されていなかったりします。
ググれば一発だろ! と思っても何故かすんなりは見つからないか、見つかっても冗長だったりするので毎回新たに書いているのですが、今回で最後にしたいのでここに貼りつけておきます。
エンコードは今回必要無かったので作ってませんが必要になった時に作ります。
urlDecode()にバッファとその長さと変換したい文字列を渡します。
なんか見本で見かけるソースよりやけに短くなってしまうのですが、何か自分が間違っているんだろうか・・・。(RFCは読んでいない)
9 :int valueFromHexChar(char hex)
10 :{
11 : if('0' <= hex && hex <= '9') return hex - '0';
12 : else if('A' <= hex && hex <= 'F') return hex - 'A' +10;
13 : else if('a' <= hex && hex <= 'f') return hex - 'a' +10;
14 : else return 0;
15 :}
16 :
17 ://typedef unsigned int size_t;
18 :void urlDecode(char* decoded
19 : ,size_t decoded_length
20 : ,const char* source)
21 :{
22 : decoded_length--; //最後の\0の分
23 : while(*source && decoded_length){
24 : if(*source == '%'){
25 : if(*(source+1) == '\0') break; //%の後2Byte続かずに備えて
26 : *(decoded++)
27 : = (valueFromHexChar( *(source+1) ) <<4 )
28 : + valueFromHexChar( *(source+2) );
29 : source += 3;
30 : }else if(*source == '+'){
31 : *(decoded++) = ' ';
32 : source++;
33 : }else{
34 : *(decoded++) = *(source++);
35 : }
36 : decoded_length--;
37 : }
38 : *decoded = '\0';
39 :}