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

2 Answers

0 votes
#include <iostream>

using namespace std;

const char *FormatBytes(long long bytes, char *str);

int main()
{
	char s[32] = "";

	cout << FormatBytes(9823453784599, s) << endl;
	cout << FormatBytes(7124362542, s) << endl;
	cout << FormatBytes(23746178, s) << endl;
	cout << FormatBytes(1048576, s) << endl;
	cout << FormatBytes(1024000, s) << endl;
	cout << FormatBytes(873445, s) << endl;
	cout << FormatBytes(1024, s) << endl;
	cout << FormatBytes(978, s) << endl;
	cout << FormatBytes(13, s) << endl;
	cout << FormatBytes(0, s) << endl;

	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 19, 2016 by avibootz
edited Apr 22, 2016 by avibootz
0 votes
#include <iostream>

using namespace std;

char* FormatBytes(float bytes, char *str);

int main()
{
	char s[32] = "";

	cout << FormatBytes(9823453784599, s) << endl;
	cout << FormatBytes(7124362542, s) << endl;
	cout << FormatBytes(23746178, s) << endl;
	cout << FormatBytes(1048576, s) << endl;
	cout << FormatBytes(1024000, s) << endl;
	cout << FormatBytes(873445, s) << endl;
	cout << FormatBytes(1024, s) << endl;
	cout << FormatBytes(978, s) << endl;
	cout << FormatBytes(13, s) << endl;
	cout << FormatBytes(0, s) << endl;

	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.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 20, 2016 by avibootz
edited Apr 22, 2016 by avibootz
...