Humanizing byte size in C++
So, now i'm working with some C++ algorithms and need to show some info about memory usage, but the problem is, when you ask the sizeof(something)
you'll get it in bytes which is kind of useless for a user to read when working.
I mean, i would be pissed if a program said it's using 33285996544 bytes of my memory.
So i made this small function to round it to some understandable size and return as a formated string, take a look:
#include <string>
string hByte(unsigned int bytes){
string r;
if (bytes <= 0) r = "0 Bytes";
else if (bytes >= 1073741824) r = to_string(bytes/1073741824) + " GBytes";
else if (bytes >= 1048576) r = to_string(bytes/1048576) + " MBytes";
else if (bytes >= 1024) r = to_string(bytes/1024) + " KBytes";
return r;
};
edited: changed to unsigned int
in the argument.
Written by Leonardo Koch Kewitz
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Leokewitz
Authors
kewitz
32.96K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#