How to format bytes to kilobytes, megabytes, gigabytes and terabytes in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
  
const char *FormatBytes(long long bytes, char *str);
  
int main(void)
{
    char s[32] = "";
     
    printf("%s\n", FormatBytes(9823453784599, s)); 
    printf("%s\n", FormatBytes(7124362542, s));
    printf("%s\n", FormatBytes(23746178, s));
    printf("%s\n", FormatBytes(1048576, s));
    printf("%s\n", FormatBytes(1024000, s));
    printf("%s\n", FormatBytes(873445, s));
    printf("%s\n", FormatBytes(1024, s));
    printf("%s\n", FormatBytes(978, s));
    printf("%s\n", FormatBytes(13, s));
    printf("%s\n", FormatBytes(0, s));
     
    return 0;
}
const char *FormatBytes(long long bytes, char *str)
{
    const char *sizes[5] = { "B", "KB", "MB", "GB", "TB" };
 
    int i;
    double dblByte = bytes;
    for (i = 0; i < 5 && bytes >= 1024; i++, bytes /= 1024) 
        dblByte = bytes / 1024.0;
 
    sprintf(str, "%.2f", dblByte);
     
    return strcat(strcat(str,  " "), sizes[i]);
}
 
 
/*
run:
 
8.93 TB
6.63 GB
22.65 MB
1.00 MB
1000.00 KB
852.97 KB
1.00 KB
978.00 B
13.00 B
0 B
 
*/

 



answered Apr 18, 2016 by avibootz
edited Apr 22, 2016 by avibootz
0 votes
#include <stdio.h>
 
char* FormatBytes(float Bytes, char *str);
 
int main(void)
{
	char s[32] = "";
	
	printf("%s\n", FormatBytes(9823453784599, s)); 
	printf("%s\n", FormatBytes(7124362542, s));
	printf("%s\n", FormatBytes(23746178, s));
	printf("%s\n", FormatBytes(1048576, s));
	printf("%s\n", FormatBytes(1024000, s));
	printf("%s\n", FormatBytes(873445, s));
	printf("%s\n", FormatBytes(1024, s));
	printf("%s\n", FormatBytes(978, s));
	printf("%s\n", FormatBytes(13, s));
	printf("%s\n", FormatBytes(0, s));
    
    return 0;
}
char* FormatBytes(float bytes, char *str)
{
	float tb = 1099511627776;
	float gb = 1073741824;
	float mb = 1048576;
	float kb = 1024;
                 
	if (bytes >= tb)
		sprintf(str, "%.2f TB", (float)bytes/tb);        
	else if (bytes >= gb && bytes < tb)
			 sprintf(str, "%.2f GB", (float)bytes/gb);
		 else if (bytes >= mb && bytes < gb)
				  sprintf(str, "%.2f MB", (float)bytes/mb);   
			  else if (bytes >= kb && bytes < mb)
                       sprintf(str, "%.2f KB", (float)bytes/kb);
                   else if (bytes < kb)
                            sprintf(str, "%.2f Bytes", bytes);
                        else
                            sprintf(str, "%.2f Bytes", bytes);

	return str;
}


/*
run:

8.93 TB
6.64 GB
22.65 MB
1.00 MB
1000.00 KB
852.97 KB
1.00 KB
978.00 Bytes
13.00 Bytes
0.00 Bytes

*/

 



answered Apr 19, 2016 by avibootz
...