开发者

How to convert human readable memory size into bytes?

I'm trying to convert strings开发者_如何学JAVA that match /(\d)+(\.\d+)?(m|g|t)?b?/i into bytes.

For example, 1KB would return 1024. 1.2mb would return 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:

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

Although 1258291 is clearly far too many significant digits to get from 1.2MB.

oops, I gave a C# example. 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜