如何在 Kotlin 中将字节大小转换为人类可读的格式?

Ebr*_*owi 1 formatting kotlin

在 StackOverflow 中找不到类似的话题,问题类似于How to convert byte size into human readable format in java?

如何在 Java 中将字节大小转换为人类可读的格式?比如 1024 应该变成“1 Kb”,而 1024*1024 应该变成“1 Mb”。

我有点厌倦为每个项目编写这种实用方法。Apache Commons 中是否有任何静态方法?

但是对于 Kotlin,已经根据那里接受的答案准备了一些东西并想分享它,但认为应该将其发布在单独的线程中最好不要分散该线程上的人们的注意力,因此其他人也可以在此处发表评论或发布其他惯用的 Kotlin 答案

Ebr*_*owi 5

基于@aioobe 的这个Java 代码:

fun humanReadableByteCountBin(bytes: Long) = when {
    bytes == Long.MIN_VALUE || bytes < 0 -> "N/A"
    bytes < 1024L -> "$bytes B"
    bytes <= 0xfffccccccccccccL shr 40 -> "%.1f KiB".format(bytes.toDouble() / (0x1 shl 10))
    bytes <= 0xfffccccccccccccL shr 30 -> "%.1f MiB".format(bytes.toDouble() / (0x1 shl 20))
    bytes <= 0xfffccccccccccccL shr 20 -> "%.1f GiB".format(bytes.toDouble() / (0x1 shl 30))
    bytes <= 0xfffccccccccccccL shr 10 -> "%.1f TiB".format(bytes.toDouble() / (0x1 shl 40))
    bytes <= 0xfffccccccccccccL -> "%.1f PiB".format((bytes shr 10).toDouble() / (0x1 shl 40))
    else -> "%.1f EiB".format((bytes shr 20).toDouble() / (0x1 shl 40))
}
Run Code Online (Sandbox Code Playgroud)

可以通过使用 ULong 删除第一个条件来改进,但当前 (2019) 类型被语言标记为实验性的。将 Locale.ENGLISH 前置到 .format( 以确保不会在具有不同数字的语言环境中转换数字。

让我知道可以改进什么,使其成为更惯用和可读的 Kotlin 代码。


Ebr*_*owi 5

因为我的用例是用于 Android 的,所以我可以使用这个/sf/answers/1855170131/

android.text.format.Formatter.formatShortFileSize(activityContext, bytes)
Run Code Online (Sandbox Code Playgroud)

android.text.format.Formatter.formatFileSize(activityContext, bytes)
Run Code Online (Sandbox Code Playgroud)


Joh*_*Doe 5

有一个更简洁的解决方案:

fun bytesToHumanReadableSize(bytes: Double) = when {
        bytes >= 1 shl 30 -> "%.1f GB".format(bytes / (1 shl 30))
        bytes >= 1 shl 20 -> "%.1f MB".format(bytes / (1 shl 20))
        bytes >= 1 shl 10 -> "%.0f kB".format(bytes / (1 shl 10))
        else -> "$bytes bytes"
    }
Run Code Online (Sandbox Code Playgroud)