Converting bytes to GB in C#?

前端 未结 13 967
孤城傲影
孤城傲影 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:26

    To make sure that the compiler pre-calculates the divisors:

    decimal GB = KB / (1024 * 1024);
    

    Note that you are actually calculating GiB (gibibyte), not GB (gigabyte). If you really want to calculate GB, that would be:

    decimal GB = KB / (1000 * 1000);
    

提交回复
热议问题