如何在Kotlin中将字节大小转换为人类可读的格式? [英] How to convert byte size into human readable format in Kotlin?

查看:176
本文介绍了如何在Kotlin中将字节大小转换为人类可读的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

未能在StackOverflow中找到类似的主题,问题类似于如何在Java中将字节大小转换为人类可读的格式?

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

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

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

我有点讨厌为每个项目编写此实用程序方法. Apache Commons中有为此使用的静态方法吗?

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

但是对于Kotlin来说,它是根据那里已被接受的答案进行准备的,并希望与他人分享,但认为应该将其发布到最好使用单独的线程,以免分散人们对该线程的注意力,以便其他人也可以在此处评论或发布其他惯用的Kotlin答案

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

推荐答案

基于@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.

这篇关于如何在Kotlin中将字节大小转换为人类可读的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆