Skip to content

Instantly share code, notes, and snippets.

@adityaramesh
Last active February 15, 2016 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adityaramesh/8d96cffb72621c20f5ef to your computer and use it in GitHub Desktop.
Save adityaramesh/8d96cffb72621c20f5ef to your computer and use it in GitHub Desktop.
Converts a human-readable memory string (e.g. "256 GiB") into an integral byte count.
import re
def parse_memory_string(mem_str):
"""
Returns the number of bytes represented by a string ``mem_str`` matching the following
regex: ::
r'^(0|[1-9][0-9]*) (byte|bytes|KiB|MiB|GiB|TiB)'
If ``mem_str`` does not match this regex, then ``None`` is returned.
"""
memory_regex = r'^(0|[1-9][0-9]*) (byte|bytes|KiB|MiB|GiB|TiB)'
mem_pat = re.compile(memory_regex)
match = mem_pat.match(mem_str)
if match is None:
return
assert len(match.groups()) == 2
base = int(match.groups()[0])
return base * {
'byte': 1,
'bytes': 1,
'KiB': 2 ** 10,
'MiB': 2 ** 20,
'GiB': 2 ** 30,
'TiB': 2 ** 40
}[match.groups()[1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment