"bytes to human readable, and back. without data loss" Code Answer

2

so it turns out the answer was much simpler than i thought - one of the links that i provided actually led to a much more detailed version of the function:

which is able to deal with any scope i give it.

but thank you for your help:

the code copied here for posterity:

## {{{ http://code.activestate.com/recipes/578019/ (r15)
#!/usr/bin/env python

"""
bytes-to-human / human-to-bytes converter.
based on: http://goo.gl/ktqms
working with python 2.x and 3.x.

author: giampaolo rodola' <g.rodola [at] gmail [dot] com>
license: mit
"""

# see: http://goo.gl/ktqms
symbols = {
    'customary'     : ('b', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y'),
    'customary_ext' : ('byte', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa',
                       'zetta', 'iotta'),
    'iec'           : ('bi', 'ki', 'mi', 'gi', 'ti', 'pi', 'ei', 'zi', 'yi'),
    'iec_ext'       : ('byte', 'kibi', 'mebi', 'gibi', 'tebi', 'pebi', 'exbi',
                       'zebi', 'yobi'),
}

def bytes2human(n, format='%(value).1f %(symbol)s', symbols='customary'):
    """
    convert n bytes into a human readable string based on format.
    symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
    see: http://goo.gl/ktqms

      >>> bytes2human(0)
      '0.0 b'
      >>> bytes2human(0.9)
      '0.0 b'
      >>> bytes2human(1)
      '1.0 b'
      >>> bytes2human(1.9)
      '1.0 b'
      >>> bytes2human(1024)
      '1.0 k'
      >>> bytes2human(1048576)
      '1.0 m'
      >>> bytes2human(1099511627776127398123789121)
      '909.5 y'

      >>> bytes2human(9856, symbols="customary")
      '9.6 k'
      >>> bytes2human(9856, symbols="customary_ext")
      '9.6 kilo'
      >>> bytes2human(9856, symbols="iec")
      '9.6 ki'
      >>> bytes2human(9856, symbols="iec_ext")
      '9.6 kibi'

      >>> bytes2human(10000, "%(value).1f %(symbol)s/sec")
      '9.8 k/sec'

      >>> # precision can be adjusted by playing with %f operator
      >>> bytes2human(10000, format="%(value).5f %(symbol)s")
      '9.76562 k'
    """
    n = int(n)
    if n < 0:
        raise valueerror("n < 0")
    symbols = symbols[symbols]
    prefix = {}
    for i, s in enumerate(symbols[1:]):
        prefix[s] = 1 << (i+1)*10
    for symbol in reversed(symbols[1:]):
        if n >= prefix[symbol]:
            value = float(n) / prefix[symbol]
            return format % locals()
    return format % dict(symbol=symbols[0], value=n)

def human2bytes(s):
    """
    attempts to guess the string format based on default symbols
    set and return the corresponding bytes as an integer.
    when unable to recognize the format valueerror is raised.

      >>> human2bytes('0 b')
      0
      >>> human2bytes('1 k')
      1024
      >>> human2bytes('1 m')
      1048576
      >>> human2bytes('1 gi')
      1073741824
      >>> human2bytes('1 tera')
      1099511627776

      >>> human2bytes('0.5kilo')
      512
      >>> human2bytes('0.1  byte')
      0
      >>> human2bytes('1 k')  # k is an alias for k
      1024
      >>> human2bytes('12 foo')
      traceback (most recent call last):
          ...
      valueerror: can't interpret '12 foo'
    """
    init = s
    num = ""
    while s and s[0:1].isdigit() or s[0:1] == '.':
        num += s[0]
        s = s[1:]
    num = float(num)
    letter = s.strip()
    for name, sset in symbols.items():
        if letter in sset:
            break
    else:
        if letter == 'k':
            # treat 'k' as an alias for 'k' as per: http://goo.gl/ktqms
            sset = symbols['customary']
            letter = letter.upper()
        else:
            raise valueerror("can't interpret %r" % init)
    prefix = {sset[0]:1}
    for i, s in enumerate(sset[1:]):
        prefix[s] = 1 << (i+1)*10
    return int(num * prefix[letter])


if __name__ == "__main__":
    import doctest
    doctest.testmod()
## end of http://code.activestate.com/recipes/578019/ }}}
By Gregor Petrin on August 6 2022

Answers related to “bytes to human readable, and back. without data loss”

Only authorized users can answer the Search term. Please sign in first, or register a free account.