二进制人类可读到实际大小
Binary Human Readable to Real Size
我想将人类可读大小(例如“10Mi”)转换回实数大小
我写了以下内容,但我似乎在转换中遗漏了一些东西
function humanFileSizeToSize (sizeString) {
const units = ['Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
const unitString = units.find(unit => sizeString.includes(unit));
const power = units.indexOf(unitString) + 1;
const size = parseFloat(sizeString.slice(0, sizeString.indexOf(unitString)))
return parseInt(size * (1024**power));
}
console.log(humanFileSizeToSize("10Mi"))
console.log(humanFileSizeToSize("1.5Mi"))
假设 1 MiB 等于 1048576 字节,似乎按预期工作。
不过可以缩短,并且无需库即可完成
const units = [, 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
const re = /(\d+(?:\.\d+)?)([KMGTPEZYi]{2})/g;
const humanFileSizeToSize = sizeString => {
const [[_,size,unit]] = sizeString.matchAll(re);
const power = units.indexOf(unit)
return parseInt(size * (1024 ** power));
}
console.log(humanFileSizeToSize("1Ki"))
console.log(humanFileSizeToSize("1Mi"))
console.log(humanFileSizeToSize("1.5Mi"))
console.log(humanFileSizeToSize("10Mi"))
console.log(humanFileSizeToSize("1Gi"))
我想将人类可读大小(例如“10Mi”)转换回实数大小
我写了以下内容,但我似乎在转换中遗漏了一些东西
function humanFileSizeToSize (sizeString) {
const units = ['Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
const unitString = units.find(unit => sizeString.includes(unit));
const power = units.indexOf(unitString) + 1;
const size = parseFloat(sizeString.slice(0, sizeString.indexOf(unitString)))
return parseInt(size * (1024**power));
}
console.log(humanFileSizeToSize("10Mi"))
console.log(humanFileSizeToSize("1.5Mi"))
假设 1 MiB 等于 1048576 字节,似乎按预期工作。
不过可以缩短,并且无需库即可完成
const units = [, 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
const re = /(\d+(?:\.\d+)?)([KMGTPEZYi]{2})/g;
const humanFileSizeToSize = sizeString => {
const [[_,size,unit]] = sizeString.matchAll(re);
const power = units.indexOf(unit)
return parseInt(size * (1024 ** power));
}
console.log(humanFileSizeToSize("1Ki"))
console.log(humanFileSizeToSize("1Mi"))
console.log(humanFileSizeToSize("1.5Mi"))
console.log(humanFileSizeToSize("10Mi"))
console.log(humanFileSizeToSize("1Gi"))