How to convert byte size into human readable format in Kotlin?

蹲街弑〆低调 提交于 2019-12-25 01:38:31

问题


Failed to find the similar topic in StackOverflow, the question is similar to How to convert byte size into human readable format in java?

How to convert byte size into human-readable format in Java? Like 1024 should become "1 Kb" and 1024*1024 should become "1 Mb".

I am kind of sick of writing this utility method for each project. Are there any static methods in Apache Commons for this?

But for Kotlin, had prepared something based on the accepted answer there and wanted to share it but thought should posting it in a separate thread is better to not distract people on that thread so others also can comment or post other idiomatic Kotlin answers here


回答1:


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

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.

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




回答2:


As my usecase was for Android use turned out https://stackoverflow.com/a/26502430 was sufficient for me, just wanted to mention how my code turned out at the end.

android.text.format.Formatter.formatShortFileSize(activityContext, bytes)

and

android.text.format.Formatter.formatFileSize(activityContext, bytes)


来源:https://stackoverflow.com/questions/59234916/how-to-convert-byte-size-into-human-readable-format-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!