字符串转换为char时字符串是一个有效的字符

编程入门 行业动态 更新时间:2024-10-23 20:23:04
本文介绍了字符串转换为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时字符串是一个有效的字符

本文发布于:2023-07-28 14:12:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1231660.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   是一个   转换为   字符   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!