1

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};
4
  • possible duplicate of How to convert/parse from String to char in java? Commented May 7, 2014 at 13:30
  • 2
    @UrsulRosu - that would return "0" for him. Not what he wants Commented May 7, 2014 at 13:31
  • 2
    not a duplicate, and I don't understand why this was downvoted. That's a good question, properly asked, with enough information to try and answer it. Commented May 7, 2014 at 13:31
  • @njzk2 Removed close vote. That was for the question before his edit... :) Commented May 7, 2014 at 13:35

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

see stackoverflow.com/a/11377996/671543 no need to strip the 0x, decode does that
@Mena - Isn't it possible without stripping 0x ? Can't I get char 0x7D ?
@VedPrakash see my edit, after njzk2's suggestion. The decode method will do just that. However you'll need to double cast.
0

Integer.parseInt(String) returns an Integer representation of the given String from which you can then obtain the character.

Comments

0
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).

2 Comments

Isn't it possible without stripping 0x ? Can't I get char 0x7D ?
@VedPrakash: No. The documentation states that the string can only contain +, - and digits of the specified radix (in this case, 0 - 9, a - f, A - F).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.