Convert khz value from CPU into mhz or ghz

2019-09-01 15:35发布

I want to convert the String (result) of the following function into an Integer value and divide it by 1000 (khz -> mhz)

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


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

result = result.replace("\n", "");
result = result.replace(" ", "");

return result;


}

This return gives me a string, f.e. 192000 (khz). But I want a mhz value..

With:

int mhz = Integer.parseInt(result)

the app closes itself..

How can I convert the khz value into mhz?

Without the .replace lines I got an error. Logcat says: " invalid int: "192000 " and after this number there are a lot of special characters like diamonds..

So I do not know how I could get the right value..

Could you help me please?

There's something wrong with the result value I think.

Thank you

1条回答
小情绪 Triste *
2楼-- · 2019-09-01 16:18

Before converting that numbrer to int, remove all non numeric characters using something like this:

int khz = result.replace("[^0-9]+", "");

Then conver khz to number and divide it by 1000.

查看更多
登录 后发表回答