Skip to content

Instantly share code, notes, and snippets.

@ioistired
Created August 19, 2017 18:03
Show Gist options
  • Save ioistired/2e9b03145f468a12debd94d06c0fcfc4 to your computer and use it in GitHub Desktop.
Save ioistired/2e9b03145f468a12debd94d06c0fcfc4 to your computer and use it in GitHub Desktop.
Convert bytes to human readable units
#!/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