Skip to content

BV 转 AV

引言

许久之前从知乎上看到的算法,如何看待 2020 年 3 月 23 日哔哩哔哩将稿件的「av 号」变更为「BV 号」?,现在使用 TypeScript 重写了一遍。现在似乎新的 BV 号已经无法转换了,也就是 AV 消失的这一天已经来了。


转换为 AV 号:


转换为 BV 号:


代码如下:

ts
const table = "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF";
const tr = [];
for (let i = 0; i < 58; i++) {
  tr[table[i]] = i;
}
const s = [11, 10, 3, 8, 4, 6];

const xor = 177451812;
const add = 8728348608;

/**
 * BV 转 AV
 */
export function dec(bv: string): number {
  let r = 0;
  for (let i = 0; i < 6; i++) {
    r += tr[bv[s[i]]] * 58 ** i;
  }
  return (r - add) ^ xor;
}

/**
 * AV 转 BV
 */
export function enc(av: string): string {
  let x = Number.parseInt(av.replace(/^av/i, ""));
  x = (x ^ xor) + add;
  const r = ["B", "V", "1", " ", " ", "4", " ", "1", " ", "7", " ", " "];
  for (let i = 0; i < 6; i++) {
    r[s[i]] = table[Math.floor(x / 58 ** i) % 58];
  }
  return r.join("");
}