Convert from millis to hex String

好久不见. 提交于 2019-12-12 05:39:36

问题


I want to set the current time as the major and minor values of a beacon. Lets suppose this is the current time 1465398279009. I want 9827 to be the value of the major and 9009 the value of the minor. I use a java code to call the shell script. this is my java code

Long millis = System.currentTimeMillis();
            String time=Long.toString(millis);
           // String major1=time.substring(...);
            String major1="99";
            String major2="99";
            String minor1="99";
            String minor2="99";
  ProcessBuilder pb2=new ProcessBuilder("/test.sh");
            pb2.environment().put("major1", major1);
            pb2.environment().put("major2", major2);
            pb2.environment().put("minor1", minor1);
            pb2.environment().put("minor2", minor2);
            Process script_exec = pb2.start();

and this is the content of test.sh

sudo hcitool -i hci0 cmd 0x08 0x0008 1e 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d sd fh fb 33 j2 k9 j9 23 h2 n9 g7 v7 $param1 $major1 $major2 $minor1 $minor2 c5 00

In this example I just try to put both values to 9999 and 9999, but I get 39321 as result, I think the values are converted to big endian. I get confused and I don't understand well in which type and how shall I convert the String.


回答1:


Long.toString can take two parameters. The first parameter is the number and the second parameter is the radix of the conversion.

Using a radix of 16 (Long.toString(millis, 16)) would result in a standard hexstring using [1-9a-f].




回答2:


Try this:

 String major1 = String.format("%02X", (millis >> 32) & 0xff);
 String major2 = String.format("%02X", (millis >> 16) & 0xff);
 String minor1 = String.format("%02X", (millis >> 8) & 0xff);
 String minor2 = String.format("%02X", millis & 0xff);

The code above accesses each byte out of the timestamp and assigns it to the proper field, then formats it as a two character (one byte) hex number. A two character hex number is what you want for the script.



来源:https://stackoverflow.com/questions/37707197/convert-from-millis-to-hex-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!