Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

How to convert bytes to KB or MB or GB or TB or PB in C#

1 Answer

0 votes
using System;
 
class Program
{
    private static string convert_bytes(long bytes) {
        string[] sizes = { "B", "KB", "MB", "GB", "TB", "PB" };
        double dbytes = bytes;
         
        int i = 0;
        while (i < sizes.Length && bytes >= 1024) {
             dbytes = bytes / 1024.0;
             i++;     
             bytes /= 1024;
        }
 
        return String.Format("{0:0.##} {1}", dbytes, sizes[i]);
    }
    static void Main() {
        Console.WriteLine(convert_bytes(554432));
        Console.WriteLine(convert_bytes(3554432));
        Console.WriteLine(convert_bytes(33554432));
        Console.WriteLine(convert_bytes(333554432));
        Console.WriteLine(convert_bytes(3333554432));
        Console.WriteLine(convert_bytes(33333554432));
        Console.WriteLine(convert_bytes(333333554432));
        Console.WriteLine(convert_bytes(3333333554432));
        Console.WriteLine(convert_bytes(33333333554432));
        Console.WriteLine(convert_bytes(333333333554432));
        Console.WriteLine(convert_bytes(3333333333554432));
    }
}
 

 
 
/*
run:
 
541.44 KB
3.39 MB
32 MB
318.1 MB
3.1 GB
31.04 GB
310.44 GB
3.03 TB
30.32 TB
303.16 TB
2.96 PB
 
*/

 



answered Nov 5, 2021 by avibootz
edited Nov 5, 2021 by avibootz
...