【发布时间】:2020-11-10 11:41:53
【问题描述】:
我正在尝试使用 PHP 以特定格式(炉石牌组代码)解码字符串,如下所示:
AAEBAc2xAgjAAe0E7QX3DdYRh6wC8fsCoIADC8kDqwTLBPsMhRDH0wKW6AK0/ALNiQPXiQOfmwMA
或
AAEBAf0GBAD6DoyAA6CAAw37AZwCigbJB/gHlA+CEIUQrRDy0AL2/QKJgAPRgAMA
规范(original description)是:
数据串是一个
base64编码的字节串。除非另有说明,否则后面的每个值都是一个整数,编码为
unsigned varint。
标题块
- 保留字节 0x00
- 版本(1)
- 格式
数据块
数据块被分成四对长度+数组,顺序如下:
- 英雄
- 单张卡片
- 2 份卡片
- n-copy 卡片
每对都有一个前导
varint指定数组中的项目数。对于前三个块,它们是varints的数组。对于最后一个块,它是一对varints的数组。这种结构的目标是使数据串尽可能紧凑。
我已经开始整理一些东西,但在处理原始字节方面我还是个新手。我的代码是:
// I found this to decode Variable-length quantity (varint)
function vlq_decode(array $bytes) {
$result = [];
$integer = 0;
foreach ($bytes as $byte) {
if ($integer > 0xfffffff - 0x7f) {
throw new OverflowException('The value exceeds the maximum allowed.');
}
$integer <<= 7;
$integer |= 0x7f & $byte;
if (($byte & 0x80) === 0) {
$result[] = $integer;
$integer = 0;
}
}
if (($byte & 0x80) !== 0) {
throw new InvalidArgumentException('Incomplete byte sequence.');
}
return $result;
}
$datastring = 'AAEBAc2xAgjAAe0E7QX3DdYRh6wC8fsCoIADC8kDqwTLBPsMhRDH0wKW6AK0/ALNiQPXiQOfmwMA';
$raw = base64_decode($datastring);
$byte_array = unpack('C*', $raw);
$result = vlq_decode($byte_array);
print_r($result);
我唯一确定的是base64_decode。我不知道unpack 参数是否正确,或者vlq_decode 函数是否按预期工作,因为不是我自己写的。
original site 上有 Python 和 Javascript 的参考实现,但它们超出了我的想象,我无法使用代码来实现我的工作。
更新:
该代码确实生成了一个array,看起来与我的预期相似,但许多值似乎不正确。我认为来自varint 的转换仍然有些偏离。
// this is the $result I get (wrong)
Array (
[0] => 0 // this is always 0
[1] => 1 // Version
[2] => 1 // Format
[3] => 1 // What follows is an array of length 1 (data block Heroes)
[4] => 1267842
[5] => 8 // What follows is an array of length 8 (data block single-copy cards)
[6] => 8193
[7] => 13956
[8] => 13957
[9] => 15245
[10] => 11025
[11] => 120322
[12] => 1867138
[13] => 524291
[14] => 11 // What follows is an array of length 11 (data block 2-copy cards)
[15] => 9347
[16] => 5508
[17] => 9604
[18] => 15756
[19] => 656
[20] => 1173890
[21] => 373762
[22] => 867842
[23] => 1262723
[24] => 1426563
[25] => 511363
[26] => 0 // What follows is an array of length 0 (data block n-copy cards)
)
Python 实现 (Gist) 生成不同的数字,格式略有不同,与包含 ID 数据的 the database 非常匹配(在 dbfId 字段中)
// this is the expected (correct) $result
Array (
[0] => 0
[1] => 1
[2] => 1
[3] => 1
[4] => 39117
[5] => 8
[6] => 192
[7] => 621
[8] => 749
[9] => 1783
[10] => 2262
[11] => 38407
[12] => 48625
[13] => 49184
[14] => 11
[15] => 457
[16] => 555
[17] => 587
[18] => 1659
[19] => 2053
[20] => 43463
[21] => 46102
[22] => 48692
[23] => 50381
[24] => 50391
[25] => 52639
[26] => 0
)
感谢任何帮助!
已经有一个question about this topic,但它写得很糟糕,没有代码示例,所以我再试一次。
【问题讨论】:
-
继续阅读规范。您的代码有效,前两个值正是它在盒子上所说的,第三个您从引用的枚举代码中查找 [1 表示“野生],有一个数组长度 [1],然后是 1 项,一个数组长度[8] 然后是 8 个项目,等等。
-
@Sammitch 结果起初看起来是正确的,但数字与预期的输出不匹配。如果您想再看一下,我已将两者都添加到我的问题中。我相信
varint转换在某些时候仍然会出错。 -
可能是字节序问题