c# - bytes to human readable string -


i using following code convert bytes human readable file size. 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
if convert same bytes using google converter gives 63.8gb.
idea wrong in code?

goolge screenshot:

google screenshot

@rené vogt , @bashis explanation. 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]);     } } 

there little confusion how display bytes. code correct if result trying achieve.

what showed google decimal representation. 1000m = 1km, can 1000byte = 1kb.

on other hand, there binary representation 1k = 2^10 = 1024. these representations called kibibytes, gibibytes etc.

which representation choose or requirements of customers. make obvious use avoid confusion.


Comments

Popular posts from this blog

ios - UITEXTFIELD InputView Uipicker not working in swift -

Hatching array of circles in AutoCAD using c# -