我想将十进制数转换为HEX。例如14
到E
但我希望将E
转换为两位数格式,例如0E
。这是我的代码,但它给了我一个错误。
int lightOnHours = 14;
Log.d("Two Digits", String.format("%02s",Integer.toHexString(lightOnHours));
错误消息
07-11 16:57:32.422: E/AndroidRuntime(12832): java.util.FormatFlagsConversionMismatchException: %s does not support '0'
07-11 16:57:32.422: E/AndroidRuntime(12832): at java.util.Formatter$FormatToken.checkFlags(Formatter.java:1359)
07-11 16:57:32.422: E/AndroidRuntime(12832): at java.util.Formatter.transform(Formatter.java:1440)
07-11 16:57:32.422: E/AndroidRuntime(12832): at java.util.Formatter.doFormat(Formatter.java:1079)
07-11 16:57:32.422: E/AndroidRuntime(12832): at java.util.Formatter.format(Formatter.java:1040)
07-11 16:57:32.422: E/AndroidRuntime(12832): at java.util.Formatter.format(Formatter.java:1009)
07-11 16:57:32.422: E/AndroidRuntime(12832): at java.lang.String.format(String.java:1998)
07-11 16:57:32.422: E/AndroidRuntime(12832): at java.lang.String.format(String.java:1972)
07-11 16:57:32.422: E/AndroidRuntime(12832): at com.test.digits.TestFragment2$5.onClick(TestFragment2.java:158)
07-11 16:57:32.422: E/AndroidRuntime(12832): at android.view.View.performClick(View.java:3627)
07-11 16:57:32.422: E/AndroidRuntime(12832): at android.view.View$PerformClick.run(View.java:14329)
07-11 16:57:32.422: E/AndroidRuntime(12832): at android.os.Handler.handleCallback(Handler.java:605)
07-11 16:57:32.422: E/AndroidRuntime(12832): at android.os.Handler.dispatchMessage(Handler.java:92)
07-11 16:57:32.422: E/AndroidRuntime(12832): at android.os.Looper.loop(Looper.java:137)
07-11 16:57:32.422: E/AndroidRuntime(12832): at android.app.ActivityThread.main(ActivityThread.java:4511)
07-11 16:57:32.422: E/AndroidRuntime(12832): at java.lang.reflect.Method.invokeNative(Native Method)
07-11 16:57:32.422: E/AndroidRuntime(12832): at java.lang.reflect.Method.invoke(Method.java:511)
07-11 16:57:32.422: E/AndroidRuntime(12832): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:976)
07-11 16:57:32.422: E/AndroidRuntime(12832): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:743)
07-11 16:57:32.422: E/AndroidRuntime(12832): at dalvik.system.NativeStart.main(Native Method)
谢谢!
答案 0 :(得分:6)
您可以使用
String.format("%02X", lightOnHours)
答案 1 :(得分:6)
您可以使用将整数格式化为十六进制的s
说明符,而不是使用String.format
的{{1}}格式说明符:
x
或String.format("%02x", lightOnHours)
如果您更喜欢大写十六进制:
X
答案 2 :(得分:3)
使用String.format("%02X", lightOnHours)
答案 3 :(得分:0)
尝试,
int lightOnHours = 14;
System.out.println(
Integer.toHexString(lightOnHours).length()==1
?"0"+Integer.toHexString(lightOnHours)
:Integer.toHexString(lightOnHours)
);