Converting bytes to GB in C#?

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

    Well, the formula is wrong (there's only about a million kilobytes in a gigabyte, not a thousand million) but, other than that, it's fine. Anyone used to working with these numbers will know what it means.

    One thing I would watch out for (and I don't know if this is a problem with C#) is that a compiler may not be able to optimize the x/1024/1024 if x is not a basic type. With C and integers, the compiler would quite easily turn that into a "blindingly-fast-shift-right-by-20-bits" instruction.

    If decimal is a class rather than a basic type, the compiler may have to do two divide operations. Whether this has any real impact on speed (or even whether it happens at all) is outside of my sphere of knowledge.

    One thing I'd consider changing is the actual variable names. It makes no real difference to the compiled code but I prefer longer variable names rather than abbreviations, so I'd opt for kiloBytes/gigaBytes or something like that. KB/GB is too easy to get confused with constants, depending on your coding standards.

    0 讨论(0)
提交回复
热议问题