duanhu2414 2017-06-26 13:20
浏览 21
已采纳

将字节转换为硬盘驱动器工厂(通告)空间

I pull the hard drive size from a computer and then use PHP to convert it to it's human readable size (E.G 750GB)

The problem is, the advertised space in hard drives is not the same as the actual size of the hard drive, but I want my PHP to display the advertised size.

This is my code:

function formatBytes($size, $precision = 0) {
    $base = log($size, 1024);
    $suffixes = array('', 'KB', 'MB', 'GB', 'TB');

    return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}

This is code that I found here on Stack. If I supply this with bytes for a 128GB (128035676160 bytes) hard drive, it actually displays 119GB. The expected result is 128GB. For a 1TB hard drive, the bytes are 1000204886016, and the expected result is 1TB or 1000GB, but I actually get 931GB.

A possible solution is to break the bytes string when the first 0 appears, and then I should have the expected result. 1 for 1tb, or 128 for 128GB. I'm just not sure if this will always work, and wanted a safer way to do this operation as it is important to my software.

I can't think of a logical way to do this, or even if it is possible. Any help with this problem is much appreciated.

  • 写回答

1条回答 默认 最新

  • dongshan8194 2017-06-26 13:38
    关注

    Hard drive manufacturers actually use the power of 1000 (instead of the power of 1024, which RAM and computers use) when they display the size of a hard drive in KB, MB, GB, TB etc. So simply try using 1000 and instead.

    For a more in-depth answer: https://en.wikipedia.org/wiki/Byte#Unit_multiples
    (As @domdom referred to in his comment).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路