php bencode,BEncode.php

class BEncode {

// Dictionary keys must be sorted. foreach tends to iterate over the order

// the array was made, so we make a new one in sorted order. :)

function makeSorted($array) {

// Shouldn't happen!

if (empty($array))

return $array;

$i = 0;

foreach($array as $key => $dummy)

$keys[$i++] = stripslashes($key);

sort($keys);

for ($i=0; isset($keys[$i]); $i++)

$return[addslashes($keys[$i])] = $array[addslashes($keys[$i])];

return $return;

}

// Encodes strings, integers and empty dictionaries.

// $unstrip is set to true when decoding dictionary keys

function encodeEntry($entry, &$fd, $unstrip = false) {

if (is_bool($entry)) {

$fd .= 'de';

return;

}

if (is_int($entry) || is_float($entry)) {

$fd .= 'i'.$entry.'e';

return;

}

if ($unstrip)

$myentry = stripslashes($entry);

else

$myentry = $entry;

$length = strlen($myentry);

$fd .= $length.':'.$myentry;

}

// Encodes lists

function encodeList($array, &$fd) {

$fd .= 'l';

// The empty list is defined as array();

if (empty($array)) {

$fd .= 'e';

return;

}

for ($i = 0; isset($array[$i]); $i++)

$this->decideEncode($array[$i], $fd);

$fd .= 'e';

}

// Passes lists and dictionaries accordingly, and has encodeEntry handle

// the strings and integers.

function decideEncode($unknown, &$fd) {

if (is_array($unknown)) {

if (isset($unknown[0]) || empty($unknown))

return $this->encodeList($unknown, $fd);

else

return $this->encodeDict($unknown, $fd);

}

$this->encodeEntry($unknown, $fd);

}

// Encodes dictionaries

function encodeDict($array, &$fd) {

$fd .= 'd';

if (is_bool($array)) {

$fd .= 'e';

return;

}

// NEED TO SORT!

$newarray = $this->makeSorted($array);

foreach($newarray as $left => $right) {

$this->encodeEntry($left, $fd, true);

$this->decideEncode($right, $fd);

}

$fd .= 'e';

}

}

function BEncode($array) {

$string = '';

$encoder = new BEncode;

$encoder->decideEncode($array, $string);

return $string;

}

?>

一键复制

编辑

Web IDE

原始数据

按行查看

历史

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值