且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-18 11:20:59

基于@aioobe的 Java代码:>

Based on this Java code by @aioobe:

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))
}

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

Can be improved by using ULong to drop the first condition but the type, currently (2019), is marked as experimental by the language. Prepend Locale.ENGLISH to .format( to ensure digits won't be converted in locales with different digits.

让我知道可以进行哪些改进以使其变得更惯用和可读性更好的Kotlin代码.

Let me know what can be improved to make it a more idiomatic and readable Kotlin code.