Subrata

Subrata

  • NA
  • 7
  • 634

Convert KB,KiB,MB,MiB,GB,GiB,TB,TiB to bytes and vice versa

Apr 13 2020 3:42 AM
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:
  1. public static string ConvertFromBytes(double size)  
  2. {  
  3. string postfix = "Bytes";  
  4. double result = size;  
  5. if (size >= 1099511627776)  
  6. {  
  7. result = size / 1099511627776;  
  8. postfix = "TiB";  
  9. }  
  10. else if(size >= 1000000000000)  
  11. {  
  12. result = size / 1000000000000;  
  13. postfix = "TB";  
  14. }  
  15. else if (size >= 1073741824)  
  16. {  
  17. result = size / 1073741824;  
  18. postfix = "GiB";  
  19. }  
  20. else if (size >= 1000000000)  
  21. {  
  22. result = size / 1000000000;  
  23. postfix = "GB";  
  24. }  
  25. else if (size >= 1048576)  
  26. {  
  27. result = size / 1048576;  
  28. postfix = "MiB";  
  29. }  
  30. else if (size >= 1000000)  
  31. {  
  32. result = size / 1000000;  
  33. postfix = "MB";  
  34. }  
  35. else if (size >= 1024)  
  36. {  
  37. result = size / 1024;  
  38. postfix = "KiB";  
  39. }  
  40. else if (size >= 1000)  
  41. {  
  42. result = size / 1000;  
  43. postfix = "KB";  
  44. }  
  45. return result.ToString("F1") + " " + postfix;//convert to float.  
  46. }  
Function 2:
  1. public static ulong ConvertToBytes(ulong value, string unit)  
  2. {  
  3. ulong size = 0;  
  4. switch (unit)  
  5. {  
  6. case "KB":  
  7. size = value * 1024;  
  8. break;  
  9. case "MB":  
  10. size = value * 1024 * 1024;  
  11. break;  
  12. case "GB":  
  13. size = value * 1024 * 1024 * 1024;  
  14. break;  
  15. case "TB":  
  16. size = value * 1024 * 1024 * 1024 * 1024;  
  17. break;  
  18. case "PB":  
  19. size = value * 1024 * 1024 * 1024 * 1024 * 1024;  
  20. break;  
  21. default:  
  22. size = value;  
  23. break;  
  24. }  
  25. return size;  
  26. }  

Answers (1)