Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Convert bytes to human readable form Android Java

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 521
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: