Skip to content

Instantly share code, notes, and snippets.

@jmacego
Created September 2, 2020 20:44
Show Gist options
  • Save jmacego/b931361306a3835cf58a1167462e36c3 to your computer and use it in GitHub Desktop.
Save jmacego/b931361306a3835cf58a1167462e36c3 to your computer and use it in GitHub Desktop.
def bytes_to_str(size, mebi=False, precision=2):
"""Accept size in bytes, return size in string with KB, MB, GB
Will always return, increase the fields with TB, etc to prevent
103892GB or similar"""
mult = 1024 if mebi else 1000
units = {1000: ['KB', 'MB', 'GB'],
1024: ['KiB', 'MiB', 'GiB']}
for unit in units[mult]:
size = size / mult
if size < mult:
break
return '{}{}'.format(round(size, precision), unit)
def str_to_bytes(size):
RE_SIZE = re.compile(r'^([\.\d]+)([a-z])(i)?b?$')
parts = RE_SIZE.search(size.lower().replace(',', ''))
if not parts:
return int(size)
size = parts.group(1)
suffix = parts.group(2)
mult = 1024 if parts.group(3) and "i" in parts.group(3) else 1000
shift = int(suffix.translate(str.maketrans('kmgtp', '12345')))
return int(float(size) * mult ** shift)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment