How to convert human readable memory size into bytes?

algorithm, javascript

Solution

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

Problem

I'm trying to convert strings that match `/(\d)+(\.\d+)?(m|g|t)?b?/i` into bytes. For example, 1KB would return 1024. 1.2mb would return 1258291.

Original source

Related problems