简体   繁体   English

如何将人类可读的内存大小转换为字节?

[英]How to convert human readable memory size into bytes?

I'm trying to convert strings that match /(\\d)+(\\.\\d+)?(m|g|t)?b?/i into bytes.我正在尝试将匹配/(\\d)+(\\.\\d+)?(m|g|t)?b?/i字符串转换为字节。

For example, 1KB would return 1024 .例如, 1KB将返回1024 1.2mb would return 1258291 . 1.2mb将返回1258291

If you reorganize the capturing group in your regex like so: /(\\d+(?:\\.\\d+)?)\\s?(k|m|g|t)?b?/i you can do something like:如果您像这样在正则表达式中重新组织捕获组: /(\\d+(?:\\.\\d+)?)\\s?(k|m|g|t)?b?/i您可以执行以下操作:

function unhumanize(text) { 
    var powers = {'k': 1, 'm': 2, 'g': 3, 't': 4};
    var regex = /(\d+(?:\.\d+)?)\s?(k|m|g|t)?b?/i;

    var res = regex.exec(text);

    return res[1] * Math.pow(1024, powers[res[2].toLowerCase()]);
}

unhumanize('1 Kb')
# 1024
unhumanize('1 Mb')
# 1048576
unhumanize('1 Gb')
# 1073741824
unhumanize('1 Tb')
# 1099511627776

You've already got a capturing group for the unit prefix, now all you need is a lookup table:您已经获得了单位前缀的捕获组,现在您只需要一个查找表:

{ 'k', 1L<<10 },
{ 'M', 1L<<20 },
{ 'G', 1L<<30 },
{ 'T', 1L<<40 },
{ 'P', 1L<<50 },
{ 'E', 1L<<60 }

Demo: http://ideone.com/5O7Vp演示: http : //ideone.com/5O7Vp

Although 1258291 is clearly far too many significant digits to get from 1.2MB .尽管1258291显然是太多有效数字,无法从1.2MB获得。

oops, I gave a C# example.哎呀,我举了一个 C# 例子。 The method is still good though.不过方法还是不错的。

One liner solution:一个班轮解决方案:

"1.5 MB".replace(/(\d+)+(\.(\d+))?\s?(k|m|g|t)?b?/i, function(value, p1, p2, p3, p4) { return parseFloat(p1 + (p2 || ""))*({ 'K' : 1<<10, 'M' : 1<<20, 'G' : 1<<30, 'T' : 1<<40 }[p4] || 1); })

# 1572864

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM