且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JAVA中字符串到十六进制到字节转换

更新时间:2023-02-03 08:24:36

首先,如果使用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/ [ ^ ]