Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bytes to human readable string

Tags:

c#

.net

c#-4.0

I am using the following code to convert bytes to human readable file size. But it's not giving accurate result.

public static class FileSizeHelper
{
    static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
    public static string GetHumanReadableFileSize(Int64 value)
    {
        if (value < 0) { return "-" + GetHumanReadableFileSize(-value); }
        if (value == 0) { return "0.0 bytes"; }

        int mag = (int)Math.Log(value, 1024);
        decimal adjustedSize = (decimal)value / (1L << (mag * 10));

        return string.Format("{0:n2} {1}", adjustedSize, SizeSuffixes[mag]);
    }
}

Usage:

FileSizeHelper.GetHumanReadableFileSize(63861073920);

It returns 59.48 GB
But if I convert the same bytes using google converter it gives 63.8GB.
Any idea what is wrong in the code?

Goolge screenshot:

Google screenshot

@René Vogt and @bashis thanks for explanation. finally get it working using following code

public static class FileSizeHelper
{
    static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
     const long byteConversion = 1000;
    public static string GetHumanReadableFileSize(long value)
    {

        if (value < 0) { return "-" + GetHumanReadableFileSize(-value); }
        if (value == 0) { return "0.0 bytes"; }

        int mag = (int)Math.Log(value, byteConversion);
        double adjustedSize = (value / Math.Pow(1000, mag));


        return string.Format("{0:n2} {1}", adjustedSize, SizeSuffixes[mag]);
    }
}
like image 237
user964829 Avatar asked Mar 14 '23 11:03

user964829


1 Answers

There is always a little confusion about how to display bytes. Your code is correct if the result is what you are trying to achieve.

What you showed from Google is a decimal representation. So just as you say 1000m = 1km, you can say 1000byte = 1kB.

On the other hand, there is the binary representation where 1k = 2^10 = 1024. These representations are called kibiBytes, Gibibytes etc.

Which representation you choose is up to you or the requirements of your customers. Just make obvious which you use to avoid confusion.

like image 187
René Vogt Avatar answered Mar 25 '23 02:03

René Vogt