Home » Extra libraries, Code snippets, applications etc. » U++ users applications in progress and useful code snippets, including reference examples! » FormatBytes function (A helper function to format bytes.)
FormatBytes function [message #47906] |
Fri, 21 April 2017 01:18 |
Oblivion
Messages: 1112 Registered: August 2007
|
Senior Contributor |
|
|
Hello,
FormatBytes() is a very simple and useful formatter which can be used for displaying file/transfer size etc.
String FormatBytes(int64 bytes, bool kilo = false)
{
const char* base1000[] = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "YB", "ZB" };
const char* base1024[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "YiB", "ZiB" };
int base = kilo ? 1000 : 1024;
int exponent = floor(log2(bytes) / log2(base));
return bytes < base
? FormatInt64(bytes) << " " << (kilo ? base1000[0] : base1024[0])
: Format("%.1f %s", bytes / pow(base, exponent), kilo ? base1000[exponent] : base1024[exponent]);
}
Example output:
------------------------------ Base:1024(kibi)--Base:1000(kilo)
1) 1023 (bytes) -> 1023 B 1.0 KB
2) 2046 (bytes) -> 2.0 KiB 2.0 KB
3) 3069 (bytes) -> 3.0 KiB 3.1 KB
4) 4092 (bytes) -> 4.0 KiB 4.1 KB
5) 5115 (bytes) -> 5.0 KiB 5.1 KB
6) 6138 (bytes) -> 6.0 KiB 6.1 KB
7) 7161 (bytes) -> 7.0 KiB 7.2 KB
8) 8184 (bytes) -> 8.0 KiB 8.2 KB
9) 9207 (bytes) -> 9.0 KiB 9.2 KB
Since it has a simple and strict format (number/SPACE/unit) it can be parsed if needed.
Is it possible to add this, or something similar to this, to U++ formatters?
It is very handy if you work with files and data transfers.
Regards,
Oblivion
Github page: https://github.com/ismail-yilmaz
upp-components: https://github.com/ismail-yilmaz/upp-components
Bobcat the terminal emulator: https://github.com/ismail-yilmaz/Bobcat
[Updated on: Fri, 21 April 2017 08:26] Report message to a moderator
|
|
|
|
|
Re: FormatBytes function [message #48602 is a reply to message #48601] |
Sun, 06 August 2017 00:16 |
wimpie
Messages: 46 Registered: March 2013 Location: holland
|
Member |
|
|
Well I picked the same identifiers as you did for as it seemed they exist and yes for now TB is (on consumers systems) probably enough for a while. When we're at the YB and ZB there's probably an uint256 or something
|
|
|
Goto Forum:
Current Time: Sat Sep 21 01:16:39 CEST 2024
Total time taken to generate the page: 0.02775 seconds
|