C# 字节转换为人类可读字符串
我使用以下代码将字节转换为人类可读的文件大小。但是 它没有给出准确的结果C# 字节转换为人类可读字符串,c#,.net,c#-4.0,C#,.net,C# 4.0,我使用以下代码将字节转换为人类可读的文件大小。但是 它没有给出准确的结果 public static class FileSizeHelper { static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; public static string GetHumanReadableFileSize(Int64 value) {
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]);
}
}
它返回59.48 GB
但是如果我使用google converter转换相同的字节,它会给出
63.8GB
知道代码中有什么错误吗 谷歌截图: @勒内·沃格特和@bashis感谢您的解释。最后,使用以下代码使其工作
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]);
}
}
公共静态类FileSizeHelper
{
静态只读字符串[]大小uffixes={“bytes”、“KB”、“MB”、“GB”、“TB”、“PB”、“EB”、“ZB”、“YB”};
常量长字节转换=1000;
公共静态字符串GetHumanReadableFileSize(长值)
{
如果(值<0){return“-”+GetHumanReadableFileSize(-value);}
如果(值==0){返回“0.0字节”;}
intmag=(int)Math.Log(值,字节转换);
双重调整尺寸=(数值/数学功率(1000,磁悬));
返回string.Format(“{0:n2}{1}”,adjustedSize,SizeSuffix[mag]);
}
}
如果您希望收到,您的结果是正确的。然而,谷歌会返回给你
不同之处在于,提供的
x
字节是x/(1000*1000*1000)
GB和x/(1024*1024*1024)
GiB字节。对于如何显示字节总是有点困惑。如果结果是您试图实现的,那么您的代码是正确的
你从谷歌上看到的是十进制表示法。所以就像你说的1000m=1km
,你可以说1000byte=1kB
另一方面,存在二进制表示,其中1k=2^10=1024
。这些表示称为
您选择哪种代表取决于您或客户的要求。请注意,您的结果与google的Gibibyte选项相匹配,这是该领域的问题之一,关于Giga/mega是1000还是1024等的不同意见。你用
1024除以1000,谷歌显然是用1000除以gibi
或Giga
之间的差异,请不要使用(int)Math.Log(value,1024)
。它在数学上可能是正确的,但在计算上可能会引入您不希望出现的错误。一个简单的四舍五入错误可以将结果改变±1。亲爱的,非常感谢您的解释,实际上客户需要这种格式,所以更新了代码以获得类似谷歌的结果:)
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]);
}
}