hbutils.scale.size¶
- Overview:
This module provides useful utilities for handling memory size units, such as MB/KB/B. It includes functions for converting various size representations to bytes and formatting size values as human-readable strings.
size_to_bytes¶
-
hbutils.scale.size.
size_to_bytes
(size: Union[int, float, str, bitmath.Byte]) → int[source]¶ Convert any type of memory size representation to an integer value in bytes.
- Parameters:
size (Union[int, float, str, Byte]) – Any type of size information.
- Returns:
Size in bytes as an integer.
- Return type:
int
- This function can handle various input types:
Integers and floats are treated as byte values.
Strings are parsed as size representations (e.g., “23356 KB”).
Byte objects from the bitmath library are converted to their byte value.
- Examples:
>>> from hbutils.scale import size_to_bytes >>> size_to_bytes(23344) 23344 >>> size_to_bytes('23356 KB') 23356000 >>> size_to_bytes('3.54 GB') 3540000000 >>> size_to_bytes('3.54 GiB') __main__:1: UserWarning: Float detected in variable in bytes (3801046056.96), rounded integer value (3801046057) is used. 3801046057
size_to_bytes_str¶
-
hbutils.scale.size.
size_to_bytes_str
(size: Union[int, float, str, bitmath.Byte], precision: Optional[int] = None, sigfigs: Optional[int] = None, system: Literal[nist, si] = 'nist') → str[source]¶ Convert any type of memory size to a string value in the most appropriate unit.
- Parameters:
size (Union[int, float, str, Byte]) – Any type of size information.
precision (Optional[int]) – Precision for float values. Default is None, which shows the original float number.
sigfigs (Optional[int]) – Number of significant figures to use. If specified, overrides precision.
system (Literal['nist', 'si']) – The unit system to use, either
nist
(binary) orsi
(decimal). Default isnist
.
- Returns:
String formatted size value in the best unit.
- Return type:
str
This function provides a human-readable representation of size values. It automatically chooses the most appropriate unit (B, KB/KiB, MB/MiB, etc.) based on the size.
The
system
parameter allows choosing between NIST (binary, e.g., KiB) and SI (decimal, e.g., KB) units.- Examples:
>>> from hbutils.scale import size_to_bytes_str >>> size_to_bytes_str(23344) '22.796875 KiB' >>> size_to_bytes_str('23356 KB') '22.274017333984375 MiB' >>> size_to_bytes_str('3.54 GB') '3.296881914138794 GiB' >>> size_to_bytes_str('3.54 GiB') __main__:1: UserWarning: Float detected in variable in bytes (3801046056.96), rounded integer value (3801046057) is used. '3.540000000037253 GiB' >>> size_to_bytes_str('3.54 GB', precision=0) # use precision '3 GiB' >>> size_to_bytes_str('3.54 GB', precision=3) '3.297 GiB' >>> size_to_bytes_str('3.54 GB', system='si') # use GB/MB/KB instead of GiB/MiB/KiB '3.54 GB' >>> size_to_bytes_str('3.54 GB', precision=3, system='si') '3.540 GB'