Converting bytes to GB in C#?

前端 未结 13 917
孤城傲影
孤城傲影 2020-12-23 12:09

I was refactoring some old code and came across the following line of code to convert bytes to GB.

decimal GB = KB / 1024 / 1024 / 1024;

Is

13条回答
  •  [愿得一人]
    2020-12-23 12:09

    I needed it the other way around, convert from 3rd party component literal size in words (e.g. "0 bytes", "1.1 MB") into generic size in bytes. so I used it this way:

            private static long UnformatBytes(string sizeInWords)
        {
            if(string.IsNullOrWhiteSpace(sizeInWords))
                return -1;
    
            string size = sizeInWords.Split(' ').FirstOrDefault();
            double result;
            if (string.IsNullOrWhiteSpace(size) || !double.TryParse(size, out result))
            {
                Debugger.Break();
                return -1;
            }
    
            int pow;
    
            if (sizeInWords.IndexOf("byte", StringComparison.OrdinalIgnoreCase) > -1)
                pow = 0;
            else if (sizeInWords.IndexOf("kb", StringComparison.OrdinalIgnoreCase) > -1)
                pow = 1;
            else if (sizeInWords.IndexOf("mb", StringComparison.OrdinalIgnoreCase) > -1)
                pow = 2;
            else if (sizeInWords.IndexOf("gb", StringComparison.OrdinalIgnoreCase) > -1)
                pow = 3;
            else if (sizeInWords.IndexOf("tb", StringComparison.OrdinalIgnoreCase) > -1)
                pow = 4;
            else
                return -1;
    
            return System.Convert.ToInt64((result * Math.Pow(1024, pow)));
        }
    

提交回复
热议问题