我想弄清楚如何将十六进制转换为字符串和整数,以便我可以通过它的串行端口操作我的 arduino 微控制器上的 RGB 灯。我在 java 网站上找到了一个很好的例子,但是我很难理解其中的一些方法,而且我被挂断了。我可以轻松地复制粘贴此代码并使其工作,但我想完全理解它。我将在我的理解中添加评论,希望有人可以提供一些反馈。
public class HexToDecimalExample3{
public static int getDecimal(String hex){ //this is the function which we will call later and they are declaring string hex here. Can we declare string hex inside the scope..?
String digits = "0123456789ABCDEF"; //declaring string "digits" with all possible inputs in linear order for later indexing
hex = hex.toUpperCase(); //converting string to uppercase, just "in case"
int val = 0; //declaring int val. I don't get this part.
for (int i = 0; i < hex.length(); i++) //hex.length is how long the string is I think, so we don't finish the loop until all letters in string is done. pls validate this
{
char c = hex.charAt(i); //char is completely new to me. Are we taking the characters from the string 'hex' and making an indexed array of a sort? It seems similar to indexOf but non-linear? help me understand this..
int d = digits.indexOf(c); //indexing linearly where 0=1 and A=11 and storing to an integer variable
val = 16*val + d; //How do we multiply 16(bits) by val=0 to get a converted value? I do not get this..
}
return val;
}
public static void main(String args[]){
System.out.println("Decimal of a is: "+getDecimal("a")); //printing the conversions out.
System.out.println("Decimal of f is: "+getDecimal("f"));
System.out.println("Decimal of 121 is: "+getDecimal("121"));
}}
总结一下评论,主要是 char c = hex.charAt(i); AND val = 16*val + d; 我不明白的部分。
一只甜甜圈
相关分类