【问题标题】:Convert to Mhz in java/Android在 java/Android 中转换为 Mhz
【发布时间】:2013-11-28 09:47:55
【问题描述】:

我找到了这段代码来获取 CPU 频率。在安卓中:

private String ReadCPUMhz()
        {
             ProcessBuilder cmd;
             String result="";
             int resultshow = 0;

             try{
              String[] args = {"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"};
              cmd = new ProcessBuilder(args);

              Process process = cmd.start();
              InputStream in = process.getInputStream();
              byte[] re = new byte[1024];
              while(in.read(re) != -1)
               {
                 result = result + new String(re);

               }

              in.close();
             } catch(IOException ex){
              ex.printStackTrace();
             }
             return result;
        }

问题是结果是 Khz 而不是 Mhz,所以我得到类似:300000.. 我如何转换为 Mhz?一位用户前段时间写道,它使用以下方法找到了解决方案:result.trim() 正如你在这里看到的Convert khz value from CPU into mhz or ghz,但他没有解释如何使用它。有人知道吗?谢谢

【问题讨论】:

  • 你不需要除以 1000 吗?
  • 你的意思是result/1000?如果可能的话,我还会显示 1 或 2 位小数。例如 400,2 Mhz 之类的东西。我不知道你是否理解
  • return String.format("%.02f Mhz", Integer.parseInt(result)/1000f);

标签: java android type-conversion frequency


【解决方案1】:

在你提到的帖子中,错误

invalid int: "192000 "

在调用之前使用 String.trim() 确实可以避免

Integer.parseInt(result);

因为在字符串“192000”中,末尾有多余的空格需要去掉。 String 类的 trim() 方法去除前导和尾随空格:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim%28%29

所以,根据您的示例代码:

/* replace XXXX by the name of the
   class that holds method `ReadCPUMhz()`
*/
XXX instance = new XXX(); // supposing class XXX has such a constructor
String result = instance.ReadCPUMhz().trim(); // removes leading & trailing spaces
int kHzValue = Integer.parseInt(result); // result in kHz
int MHzResult = kHzValue / 1000; // result in MHz

应该以 MHz 为单位给出预期结果。

【讨论】:

    【解决方案2】:

    将您的结果除以 Khz/1000 以获得 Mhz。检查这个小数点的答案:https://stackoverflow.com/a/10959430/2065418

    tv.setText(new DecimalFormat("##.##").format(i2));
    

    【讨论】:

      猜你喜欢
      • 2012-11-12
      • 2017-04-14
      • 1970-01-01
      • 2015-07-05
      • 2013-03-22
      • 2016-12-21
      • 2013-11-29
      • 2020-11-14
      • 1970-01-01
      相关资源
      最近更新 更多