在C#中将字节转换为GB?

Mic*_*ern 30 c# refactoring

我正在重构一些旧代码并遇到以下代码行将字节转换为GB.

decimal GB = KB / 1024 / 1024 / 1024;
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来重构下面的代码?

更新

我的意思是说千兆字节的字节数.我提供了错误的信息.

JLo*_*pez 91

我在这里开发了这种方法,可以达到TB.

private static string FormatBytes(long bytes)
{
    string[] Suffix = { "B", "KB", "MB", "GB", "TB" };
    int i;
    double dblSByte = bytes;
    for (i = 0; i < Suffix.Length && bytes >= 1024; i++, bytes /= 1024) 
    {
        dblSByte = bytes / 1024.0;
    }

    return String.Format("{0:0.##} {1}", dblSByte, Suffix[i]);
}
Run Code Online (Sandbox Code Playgroud)

  • 有点偏离主题,但我喜欢这个伎俩.+1 (3认同)

Rex*_*x M 18

如果精确度不重要,请使用double:

double gb = kb / 1048576D
Run Code Online (Sandbox Code Playgroud)

在这里同意Pavel - 没有必要重构这段代码......事实上,如果这是你的代码库中最大的问题,我想你可能会坐在编写得最好的软件上.

  • 关于使用double的+1,但我认为原始实现的意图更清晰. (2认同)

tec*_*ile 8

原始代码简洁,易于阅读,并且具有合理的变量名称,自我记录; 我不会改变它.

如果绝对必须重构,可以在数字类型上创建一组扩展方法:

public static double BytesToKilobytes(this Int32 bytes)
{
    return bytes / 1024d;
}
public static double BytesToMegabytes(this Int32 bytes)
{
    return bytes / 1024d / 1024d;
}
public static double KilobytesToBytes(this double kilobytes)
{
    return kilobytes * 1024d;
}

//You can then do something like:
double filesize = 32.5d;
double bytes = filesize.KilobytesToBytes();
Run Code Online (Sandbox Code Playgroud)

但是,除非你的代码几乎没有任何东西,只能将字节转换为千字节等,所有这一切真的会让Intellisense变得杂乱无益.


AZ_*_*AZ_ 6

    /// <summary>
/// Function to convert the given bytes to either Kilobyte, Megabyte, or Gigabyte
/// </summary>
/// <param name="bytes">Double -> Total bytes to be converted</param>
/// <param name="type">String -> Type of conversion to perform</param>
/// <returns>Int32 -> Converted bytes</returns>
/// <remarks></remarks>
public static double ConvertSize(double bytes, string type)
{
    try
    {
        const int CONVERSION_VALUE = 1024;
        //determine what conversion they want
        switch (type)
        {
            case "BY":
                 //convert to bytes (default)
                 return bytes;
            case "KB":
                 //convert to kilobytes
                 return (bytes / CONVERSION_VALUE);
            case "MB":
                 //convert to megabytes
                 return (bytes / CalculateSquare(CONVERSION_VALUE));
            case "GB":
                 //convert to gigabytes
                 return (bytes / CalculateCube(CONVERSION_VALUE));
            default:
                 //default
                 return bytes;
          }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return 0;
      }
}

/// <summary>
/// Function to calculate the square of the provided number
/// </summary>
/// <param name="number">Int32 -> Number to be squared</param>
/// <returns>Double -> THe provided number squared</returns>
/// <remarks></remarks>
public static double CalculateSquare(Int32 number)
{
     return Math.Pow(number, 2);
}


/// <summary>
/// Function to calculate the cube of the provided number
/// </summary>
/// <param name="number">Int32 -> Number to be cubed</param>
/// <returns>Double -> THe provided number cubed</returns>
/// <remarks></remarks>
public static double CalculateCube(Int32 number)
{
     return Math.Pow(number, 3);
}

//Sample Useage
String Size = "File is " + ConvertSize(250222,"MB") + " Megabytes in size"
Run Code Online (Sandbox Code Playgroud)