diff --git a/src/hasp/hasp_utilities.cpp b/src/hasp/hasp_utilities.cpp index 3cdd6386..75ab5cd8 100644 --- a/src/hasp/hasp_utilities.cpp +++ b/src/hasp/hasp_utilities.cpp @@ -31,4 +31,20 @@ bool hasp_util_is_only_digits(const char * s) digits++; } return strlen(s) == digits; +} + +int hasp_util_format_bytes(size_t filesize, char * buf, size_t len) +{ + if(filesize < 1024) return snprintf_P(buf, len, PSTR("%d B"), filesize); + + char labels[] = "kMGT"; + filesize = filesize * 10 / 1024; // multiply by 10 for 1 decimal place + int unit = 0; + + while(filesize >= 10240 && unit < sizeof(labels) - 1) { // it is multiplied by 10 + unit++; + filesize = filesize / 1024; + } + + return snprintf_P(buf, len, PSTR("%d.%d %ciB"), filesize / 10, filesize % 10, labels[unit]); } \ No newline at end of file diff --git a/src/hasp/hasp_utilities.h b/src/hasp/hasp_utilities.h index fa99fe24..eb164cd5 100644 --- a/src/hasp/hasp_utilities.h +++ b/src/hasp/hasp_utilities.h @@ -7,5 +7,6 @@ uint16_t hasp_util_get_sdbm(const char * str); bool hasp_util_is_true(const char * s); bool hasp_util_is_only_digits(const char * s); +int hasp_util_format_bytes(size_t filesize, char * buf, size_t len); #endif \ No newline at end of file diff --git a/src/hasp_hal.cpp b/src/hasp_hal.cpp index 41028806..aa0323d0 100644 --- a/src/hasp_hal.cpp +++ b/src/hasp_hal.cpp @@ -293,26 +293,7 @@ uint16_t halGetCpuFreqMHz() #endif } -String halFormatBytes(size_t bytes) -{ - String output((char *)0); - output.reserve(128); - if(bytes < 1024) { - output += bytes; - } else if(bytes < (1024 * 1024)) { - output += bytes / 1024.0; - output += "K"; - } else if(bytes < (1024 * 1024 * 1024)) { - output += bytes / 1024.0 / 1024.0; - output += "M"; - } else { - output += bytes / 1024.0 / 1024.0 / 1024.0; - output += "G"; - } - output += "B"; - return output; -} String halDisplayDriverName() { diff --git a/src/hasp_hal.h b/src/hasp_hal.h index e5163633..5c735bab 100644 --- a/src/hasp_hal.h +++ b/src/hasp_hal.h @@ -15,7 +15,6 @@ String halGetCoreVersion(void); String halGetChipModel(); String halGetMacAddress(int start, const char * seperator); uint16_t halGetCpuFreqMHz(void); -String halFormatBytes(size_t bytes); String halDisplayDriverName(void); String halGpioName(uint8_t gpio);