Need to convert incoming input in units KB,KiB,MB,MiB,GB,GiB,TB,TiB to bytes to display as output.
Also, Need to convert incoming input in bytes to best suited units KB,KiB,MB,MiB,GB,GiB,TB,TiB and give as output.
Also, have to be sure of precision and convert to the best possible unit.
I tried the below. Is there any better way to code this?Could someone please help me?
Function 1:
- public static string ConvertFromBytes(double size)
- {
- string postfix = "Bytes";
- double result = size;
- if (size >= 1099511627776)
- {
- result = size / 1099511627776;
- postfix = "TiB";
- }
- else if(size >= 1000000000000)
- {
- result = size / 1000000000000;
- postfix = "TB";
- }
- else if (size >= 1073741824)
- {
- result = size / 1073741824;
- postfix = "GiB";
- }
- else if (size >= 1000000000)
- {
- result = size / 1000000000;
- postfix = "GB";
- }
- else if (size >= 1048576)
- {
- result = size / 1048576;
- postfix = "MiB";
- }
- else if (size >= 1000000)
- {
- result = size / 1000000;
- postfix = "MB";
- }
- else if (size >= 1024)
- {
- result = size / 1024;
- postfix = "KiB";
- }
- else if (size >= 1000)
- {
- result = size / 1000;
- postfix = "KB";
- }
- return result.ToString("F1") + " " + postfix;
- }
Function 2:
- public static ulong ConvertToBytes(ulong value, string unit)
- {
- ulong size = 0;
- switch (unit)
- {
- case "KB":
- size = value * 1024;
- break;
- case "MB":
- size = value * 1024 * 1024;
- break;
- case "GB":
- size = value * 1024 * 1024 * 1024;
- break;
- case "TB":
- size = value * 1024 * 1024 * 1024 * 1024;
- break;
- case "PB":
- size = value * 1024 * 1024 * 1024 * 1024 * 1024;
- break;
- default:
- size = value;
- break;
- }
- return size;
- }