Converting String to char when String is a valid char

こ雲淡風輕ζ 提交于 2019-12-11 10:05:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!