How to convert readable memory size to bytes?

I am trying to convert strings matching /(\d)+(\.\d+)?(m|g|t)?b?/i to bytes.

For example, 1KB will return 1024 . 1.2mb will return 1258291 .

+2
javascript algorithm
source share
2 answers

If you reorganize the capture group in your regular expression like this: /(\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 
+7
source share

You already have a capture group for the device prefix, now you only need 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 clearly too many significant digits to get from 1.2MB .

oops, I gave an example of C #. The method is still good.

+3
source share

All Articles