JAVA中字符串到十六进制到字节转换 [英] String to Hex to Byte Conversion in JAVA
本文介绍了JAVA中字符串到十六进制到字节转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
提前致谢。
我有一种方法setpower用于设置硬件电源。
Hello All,
Thanks in advance.
I have one method setpower which is used to set hardware power.
SetHardwarePower(new byte[]{0x0a,0x14,0x14,0x14});
在上面的方法中,0x0a表示10,0x14表示20.
For API设计我写了一个方法,例如 SetRfPower(10,20,20,20)
In above method you 0x0a means in 10 , 0x14 means 20.
For API design I wrote one method For e.g. SetRfPower(10,20,20,20)
public boolean SetPower(int Power1,int Power2,int Power3,int Power4)
{
//here I have to convert int to hex
String power1inhex = "0x";
power1inhex += Integer.toHexString(Power1); // power1inhex = 0x0a
// Please help me to write code here. How should I use power1inhex string as byte to pass in method SetHardwarePower.
SetHardwarePower(new byte[]{0x0a,0x14,0x14,0x14});
}
我尝试了很多。请告诉我们任何单独的方法。
I tried a lot. please let us know any separate approach.
推荐答案
首先,如果使用int作为参数类型,则可能会遇到溢出情况。最好使用byte并在调用方法时进行类型转换(如果需要)
First of all, if you use int as your argument type you might run into an overflow situation. Better to use byte and do a type cast when you call the method (if necessary)
public boolean SetPower(byte Power1, byte Power2, byte Power3, byte Power4)
{
//here I have to convert int to hex
String power1inhex = "0x";
power1inhex += Integer.toHexString(Power1); // power1inhex = 0x0a
// Please help me to write code here. How should I use power1inhex string as byte to pass in method SetHardwarePower.
// No conversion needed. The computer will interpret your the input values as
// hexadecimal numbers automatically. (Not the best explanation, I know)
SetHardwarePower(new byte[]{Power1, Power2, Power3, Power4});
}
如果用户输入十进制值作为字符串,则只需要将字符串转换为字节。 br />
If the user is entering decimal values as a string, you only need to convert from string to byte.
string aString = "10";
byte aByte = (byte)Integer.parseInt(aString);
dec hex binary
aByte = 10 or 0x0A or 0000 1010 (it all depends on how you choose to show the value)
解决方案是阅读Java文档。
在Java文档中,您将了解到在源代码中编写整数的方法不止一种代码和相同的内容适用于用户整数输入。
任何整数都可以输入十六进制,十进制,八进制和二进制。你的μ-proc只处理二进制,所以编译器和整数输入命令将任何整数静默转换为二进制表示,无论如何。
如果用户输入是100或0144或0x64或0b1100100,你只会知道小数值100停止
你不必关心这些细节。
http://rodrigosasaki.com/2013/06/10/number-literals-in-java/ [ ^ ]
这篇关于JAVA中字符串到十六进制到字节转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文