Hi,
I’ve been wondering how Apple calculates Gigabytes in Finder, as I haven’t been able to find any function that yields the result shown.
I would like to convert 1,303,412,493 Bytes.
It says 1.3 GB in the top right corner, which matches my own conversion.
let byteCountFormatStyle = ByteCountFormatStyle(style: .file,
allowedUnits: .all,
spellsOutZero: false,
includesActualByteCount: false,
locale: Locale.current)
let sizeFormatStyle = byteCountFormatStyle.format(Int64(1_303_412_493))
let byteMeasurement = Measurement(value: Double(1_303_412_493), unit: UnitInformationStorage.bytes)
let sizeMeasurement = byteMeasurement.formatted(.byteCount(style: .file))
print("sizeFormatStyle: \(sizeFormatStyle), sizeMeasurement: \(sizeMeasurement)")
Both are the same: sizeFormatStyle: 1.3 GB, sizeMeasurement: 1.3 GB
But how do I arrive at the 1.51 GB figure that appears next to the Byte count?
Christian
The Finder is showing two very different numbers here:
- 1,303,412,493 byte value, summarised as 1.3 GB at the top, is the logical size of the files.
- The 1.51 GB value is a summary of the size on disk, or physical size, of the files.
Calculating the size of a file is basically an impossible task [1], but standard practical is to account for allocation block rounding. Consider this file:
% xxd test.txt
00000000: 41 A
% ls -l test.txt
-rw-r--r--@ 1 quinn staff 1 21 Oct 10:16 test.txt
Finder reports its size as 1 byte but its size on disk as 4 KB, because it knows that a 1 byte file needs a 4 KB allocation block.
However, you shouldn’t do that rounding yourself. Rather, use the fileSize property for the logical size and the fileAllocatedSize property for the size on disk. These handle various edge cases that you don’t want to have to think about (-:
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] Even back in the day this was a matter of definition. For example, in a classic UFS file system, would you consider the bytes consumed by the inode to be part of the file size? However, these days it’s much more complicated, with things like:
- Sparse files
- Multiple forks
- Extended attributes
- ACLs
- Small files being stored in the catalogue node
- APFS clones
As with most things, when you look at file sizes in depth you realise that we’ve “made a big mistake in coming down from the trees in the first place” (-: