问题
I am doing socket communication using bluetooth in which I am getting hex values as a variables in string format.
I can write -
char char1= 0x7D;
But somehow if value 0x7D is string then how to convert that to char.
For example, I can't do -
String string1 = "0x7D";
char char1 = (char)string1;
Any approach to do that ?
I want this because I can write to socket with -
char[] uploadCommand2 = {0x7d, 0x4d, 0x01, 0x00, 0x01, 0xcb};
But can't if 0x7d is a string like --
char[] uploadCommand2 = {string1, 0x4d, 0x01, 0x00, 0x01, 0xcb};
回答1:
If you strip off the 0x prefix for your hex String representation, you can use Integer.parseInt and cast to char.
See edit below for an alternative (possibly more elegant solution).
String s = "0x7D";
// | casting to char
// | | parsing integer ...
// | | | on stripped off String ...
// | | | | with hex radix
System.out.println((char)Integer.parseInt(s.substring(2), 16));
Output
}
Edit
As njzk2 points out:
System.out.println((char)(int)Integer.decode(s));
... will work as well.
回答2:
Integer.parseInt(String) returns an Integer representation of the given String from which you can then obtain the character.
回答3:
String string1 = "0x7D";
char char1 = (char) Integer.parseInt(string1.substring(2), 16);
Edit: This works, but Integer.decode() is the way to go here (thanks to njzk2).
来源:https://stackoverflow.com/questions/23519202/converting-string-to-char-when-string-is-a-valid-char