| /* Copyright 2015-2024 Rivoreo |
| |
| Permission is hereby granted, free of charge, to any person obtaining |
| a copy of this software and associated documentation files (the |
| "Software"), to deal in the Software without restriction, including |
| without limitation the rights to use, copy, modify, merge, publish, |
| distribute, sublicense, and/or sell copies of the Software, and to |
| permit persons to whom the Software is furnished to do so, subject to |
| the following conditions: |
| |
| The above copyright notice and this permission notice shall be |
| included in all copies or substantial portions of the Software. |
| |
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, |
| DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |
| OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR |
| THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| */ |
| |
| #include <stdio.h> |
| |
| long int human_readable_binary(unsigned long long int n, int *symbol, unsigned int scale) { |
| if(!symbol) return -1; |
| if(scale < 1) return -1; |
| switch(*symbol) { |
| case 0: |
| if(n < 1024 * scale) return n; |
| n /= 1024; |
| *symbol = 'K'; |
| case 'K': |
| if(n < 1024 * scale) return n; |
| n /= 1024; |
| *symbol = 'M'; |
| case 'M': |
| if(n < 1024 * scale) return n; |
| n /= 1024; |
| *symbol = 'G'; |
| case 'G': |
| if(n < 1024 * scale) return n; |
| n /= 1024; |
| *symbol = 'T'; |
| case 'T': |
| if(n < 1024 * scale) return n; |
| n /= 1024; |
| *symbol = 'P'; |
| case 'P': |
| if(n < 1024 * scale) return n; |
| n /= 1024; |
| *symbol = 'E'; |
| case 'E': |
| if(n < 1024 * scale) return n; |
| n /= 1024; |
| *symbol = 'Z'; |
| return n; |
| default: |
| return -1; |
| } |
| } |
| |
| int print_human_readable_binary(unsigned long long int n, int initial_symbol, unsigned int scale_factor, int print_width, FILE *f) { |
| if(print_width < 1) return -1; |
| int symbol = initial_symbol; |
| unsigned int scale = scale_factor ? scale_factor * 10 : 1; |
| n *= scale; |
| long int scaled_number = human_readable_binary(n, &symbol, scale); |
| if(scaled_number == -1) return -1; |
| if(symbol) { |
| fprintf(f, "%*ld", print_width - 2, scaled_number / scale); |
| if(scale > 1) fprintf(f, ".%0*ld", scale_factor, scaled_number % scale); |
| fprintf(f, " %ci", symbol); |
| } else { |
| fprintf(f, "%*ld ", print_width, scaled_number / scale); |
| } |
| return 0; |
| } |