一、aid和bvid是什么?
aid:https://www.bilibili.com/video/av1301648659/中的1301648659。
bvid:https://www.bilibili.com/video/BV1uu4m1g7Ej/中的BV1uu4m1g7Ej。
打开后可以发现,这两个链接指向的是同一个b站视频。
二、java实现
1.代码如下(示例):
public static void main(String[] args) throws Exception {
System.out.println(av2bv(1301648659));
System.out.println(bv2av("BV1uu4m1g7Ej"));
}
private static final String table = "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF";
private static final int[] s = {11, 10, 3, 8, 4, 6, 2, 9, 5, 7};
private static final int xor = 177451812;
//8728348608L 100618342136696320L
//105开头id转换:1051277039;
private static final long add_105 = 8728348608L;
private static final long add_all = 8728348608L - Integer.MAX_VALUE - 1;
private static int[] tr = new int[128];
static {
for (int i = 0; i < 58; i++) {
tr[table.charAt(i)] = i;
}
}
public static long bv2av(String x) {
long r = 0;
for (int i = 0; i < 6; i++) {
r += tr[x.charAt(s[i])] * (long) Math.pow(58, i);
}
long add = add_105;
if(r < add){
add = add_all;
}
long avid = ((r - add) ^ xor);
return avid;
}
public static String av2bv(long x) {
long add = add_105;
if(x > 1060000000){
add = add_all;
}
x = (x ^ xor) + add;
char[] r = {'B', 'V', '1', ' ', ' ', '4', ' ', '1', ' ', '7', ' ', ' '};
for (int i = 0; i < 6; i++) {
r[s[i]] = table.charAt((int)(x / (long) Math.pow(58, i) % 58));
}
return new String(r);
}
2.执行
BV1uu4m1g7Ej
1301648659
互转成功。
后语
网上有老版aid与bvid互转的实现,但是已不支持新版本转换,现在加入兼容代码,同时支持新老版本id互转。