Convert bytes data to human readable form.
1. I initialized the byte with random number;
long bytes = 123456;
2. Initialize String[] of data types.
String[] types = {"kb", "Mb", "GB", "TB", "PB", "EB"};
3. initialize unit variable.
int unit = 1024;
4. check if bytes are less then 1024 so it will returns as byte.
if (bytes < unit) return bytes + "bytes";
5. format and values of bytes to specific data type.
int exp = (int) (Math.log(bytes) / Math.log(unit));
String result = String.format("%.1f ", bytes / Math.pow(unit, exp)) + types[exp - 1];
Full Code:-
long bytes = 123456;
String[] types = {"kb", "Mb", "GB", "TB", "PB", "EB"};
int unit = 1000;
if (bytes < unit) return bytes + "bytes";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String result = String.format("%.1f ", bytes / Math.pow(unit, exp)) + types[exp - 1];
Happy Coding :D
0 Comment(s)