I’ve made a simple function that converts a file size to a string. It computes the remainder after dividing the input size by 1024 and puts it in an array. This step is being performed while we have a size under 1024 – this is the number of the bytes.
1 2 3 4 5 6 7 8 9 10 11 |
uint[] s = new uint[7]; short n = 0; while (size >= 1024) { s[n] = (uint)(size % 1024); size = size / 1024; n++; } s[n] = (uint)size; |
The type of size is Int64. It allows you to calculate too big numbers. After filling up the array, you can start walking it from its end like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
StringBuilder results = new StringBuilder(); string[] sizes = { "bytes(s)", "KB", "MB", "GB", "TB", "PB", "EB" }; for(n = 6; n >= 0; n--) { if (s[n] > 0) { result.Append(s[n]); result.Append(sizes[n]); result.Append(" "); } } |
Calling this function with argument Int64.MaxValue gives you the following result:
7EB 1023PB 1023TB 1023GB 1023MB 1023KB 1023bytes(s)