user497087
user497087

Reputation: 1591

how to turn string representation of a byte into a byte

I have a String that holds the string representation of a byte value.

String string = "0xOA";

how do I turn this into a byte with the value 0A?

Upvotes: 1

Views: 158

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can use

byte b = (byte) Integer.decode("0x0A");

This works for strings in octal and decimal. The reason for using Integer is that 0xFF will fail for Byte (as 255 > 127)

Upvotes: 4

Keppil
Keppil

Reputation: 46209

You can use

Byte.parseByte(string.substring(2), 16)

The .substring(2) is to get rid of the 0x, and 16 is the radix for hexadecimals.

Upvotes: 2

Adel Boutros
Adel Boutros

Reputation: 10285

Did you try Byte.valueOf(String s) ?

Upvotes: 1

triclosan
triclosan

Reputation: 5714

Try to

Byte.valueOf(string, 16);

Upvotes: 0

Related Questions