字符串转换为char时字符串是一个有效的字符 [英] Converting String to char when String is a valid char
问题描述
我使用中,我以字符串格式获取十六进制值作为一个变量,蓝牙做socket通讯。
我可以写 -
字符CHAR1 = 0x7D;
但不知何故,如果value 0x7D
是字符串那么如何将其转换为char。
例如,我不能这样做 -
字符串字符串1 =0x7D;
焦炭CHAR1 =(char)的字符串1;
的任何方法来做到这一点?
我想这是因为我可以写与在插座 -
的char [] = uploadCommand2 {0x7d,送出0x4d,0×01,0×00,0×01,0xcb};
但不能如果 0x7d
就像是一个字符串 -
的char [] = uploadCommand2 {字符串1,送出0x4d,0×01,0×00,0×01,0xcb};
如果你脱光 0X
preFIX为十六进制字符串
重新presentation,您可以使用的Integer.parseInt
和转换为字符
。
请参阅修改下面的替代(可能更优雅的解决方案)。
一个String =0x7D;
// |铸造为char
// | |解析整数...
// | | |上剥下串...
// | | | |十六进制基数
的System.out.println((炭)的Integer.parseInt(s.substring(2),16));
输出
}
修改
由于 njzk2 所指出的:
的System.out.println((char)的(INT)Integer.de code(S));
... ...将正常工作。
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};
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.
这篇关于字符串转换为char时字符串是一个有效的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!