1

I have a problem in converting String (contains hexadecimal value) to byte. Like below code.

String hexaString = "0xA1";
byte hexaByte = (byte)hexaString;

Not able to convert from String to byte like this code (Getting the Error : Cannot cast from String to byte).

But i am able to do like this

byte hexaByte = (byte)0xA1; //this is giving output as -95

Anyone please guide me how can i do like the first method(this also output the value -95). Because, the last two digit i will get from db and i need to convert it to hexadecimal(appending 0x). Then i should send to client as a byte value.

Thanks in Advance !

programmer
  • 96
  • 1
  • 2
  • 11
  • 1
    hexaString.getBytes() ? :) – Shark Nov 12 '15 at 11:00
  • 1
    @Shark looks like the `OP` is trying to convert the value as a whole – Reimeus Nov 12 '15 at 11:01
  • Possible duplicate of [How to convert string to byte in Java](http://stackoverflow.com/questions/8652804/how-to-convert-string-to-byte-in-java) – Tom Nov 12 '15 at 11:02
  • @Shark , hexaString.getBytes() this will give byte array. I want to convert the value as a whole like Reimeus said – programmer Nov 12 '15 at 11:29
  • I understand the problem, but it works-around the inability to cast Strings to bytes. Try to use unsigned bytes/ints before casting to integers. I'll dig out some of my Java code-gems that deal with bytes when I get home unless you solve it before I do :) @Reimeus thanks for helping (him) out. – Shark Nov 12 '15 at 13:48

2 Answers2

1

You can do something like:

byte hexaByte = Byte.parseByte("1A", 16);

where 16 is radix (base of system numeration), but if the number is higer than 127 it will cause NumberFormatException.

VDanyliuk
  • 1,049
  • 8
  • 23
1

If you need to be able to work with the 0x prefix, (byte) Integer.decode("0xA1") will do the right thing.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413