Question

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};
Was it helpful?

Solution

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.

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top