Created
August 19, 2017 18:03
-
-
Save ioistired/2e9b03145f468a12debd94d06c0fcfc4 to your computer and use it in GitHub Desktop.
Convert bytes to human readable units
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# encoding: utf-8 | |
import math | |
def human_readable_base2(bytes): | |
units = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB') | |
return human_readable(bytes, 1024, units) | |
def human_readable_base10(bytes): | |
units = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB') | |
return human_readable(bytes, 1000, units) | |
def human_readable(bytes, base, units): | |
size = math.log(bytes, base) | |
# round | |
approx_size = math.trunc(size + 0.1) | |
return (bytes / base**approx_size, units[approx_size]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment