在java/Android中转换为Mhz
我在Android中找到了以下代码来获取Cpu频率:在java/Android中转换为Mhz,java,android,type-conversion,frequency,Java,Android,Type Conversion,Frequency,我在Android中找到了以下代码来获取Cpu频率: private String ReadCPUMhz() { ProcessBuilder cmd; String result=""; int resultshow = 0; try{ String[] args = {"/system/bin/cat", "/sys/devices/syste
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()
正如你在这里看到的,但他没有解释如何使用它。。有人知道吗?谢谢将结果除以Khz/1000得到Mhz。请检查以下答案中的小数部分:
在你提到的帖子中,错误
invalid int: "192000 "
在调用之前使用String.trim()确实可以避免这种情况
Integer.parseInt(result);
因为在字符串“192000”中,末尾有一个额外的空格需要删除。类String的方法trim()删除前导和尾随空格:因此,根据您的示例代码:
/* 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为单位给出预期结果。您不需要除以1000吗?您的意思是
result/1000
?如果可能的话,我也会显示1或2个小数。。例如,类似于400,2
Mhz的频率。。我不知道您是否理解stream.format(“%.02f Mhz”,Integer.parseInt(result)/1000f);
/* 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