Skip to content

Instantly share code, notes, and snippets.

@gabrielstelmach
Created November 28, 2017 18:57
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 gabrielstelmach/e96aad8eb328a0adf1f83a8ce2d624a9 to your computer and use it in GitHub Desktop.
Save gabrielstelmach/e96aad8eb328a0adf1f83a8ce2d624a9 to your computer and use it in GitHub Desktop.
Retrives a friendly formated byte count
/**
* Retrieves the friendly format of the number of bytes.<br>
* Is possible to convert it using decimal base, applying <b>International System of Units (SI)</b>, or binary system.
* As result you get:
* <ul>
* <li>Following SI: 1 kB, 1 MB, 1 GB, 1 TB, 1 PB e 1 EB</li>
* <li>Binary system: 1 KiB, 1 MiB, 1 GiB, 1 TiB, 1 PiB, e 1 EiB</li>
* </ul>
* References:
* <ul>
* <li><a href="https://en.wikipedia.org/wiki/Byte">Wiki - Byte</a></li>
* <li><a href="https://en.wikipedia.org/wiki/International_System_of_Units">Wiki - International System of Units (SI)</a></li>
* </ul>
*
* @param internationalSystemUnits Identifies the use of International System of Units (SI).
* @param bytes Number of bytes.
* @return Formatted amount of bytes.
*/
public static String friendlyByteCount(boolean internationalSystemUnits, long bytes)
{
int base;
String prefix;
String friendly;
if (internationalSystemUnits)
{
//International System of Units (SI) uses decimal base
base = 1000;
}
else
{
base = 1024;
}
if (bytes < base)
{
friendly = bytes + " B";
}
else
{
int log = (int)(Math.log(bytes) / Math.log(base));
if (internationalSystemUnits)
{
prefix = "kMGTPE".charAt(log - 1) + "B";
}
else
{
prefix = "KMGTPE".charAt(log - 1) + "iB";
}
double count = bytes / Math.pow(base, log);
friendly = (count + " " + prefix);
}
return friendly;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment