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};
sjain
  • 23,126
  • 28
  • 107
  • 185
  • possible duplicate of [How to convert/parse from String to char in java?](http://stackoverflow.com/questions/7853502/how-to-convert-parse-from-string-to-char-in-java) – Pankaj Kumar May 07 '14 at 13:30
  • 2
    @UrsulRosu - that would return "0" for him. Not what he wants – dymmeh May 07 '14 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. – njzk2 May 07 '14 at 13:31
  • @njzk2 Removed close vote. That was for the question before his edit... :) – Pankaj Kumar May 07 '14 at 13:35

3 Answers3

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.

Community
  • 1
  • 1
Mena
  • 47,782
  • 11
  • 87
  • 106
  • 2
    see http://stackoverflow.com/a/11377996/671543 no need to strip the 0x, `decode` does that – njzk2 May 07 '14 at 13:34
  • @Mena - Isn't it possible without stripping 0x ? Can't I get char `0x7D` ? – sjain May 07 '14 at 14:08
  • @VedPrakash see my edit, after njzk2's suggestion. The `decode` method will do just that. However you'll need to double cast. – Mena May 07 '14 at 14:11
0

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

schubakah
  • 425
  • 4
  • 13
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).

Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
  • Isn't it possible without stripping 0x ? Can't I get char `0x7D` ? – sjain May 07 '14 at 14:10
  • @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`). – Gabriel Negut May 07 '14 at 14:17