2

Possible Duplicate:
Convert a hex string to a byte in Java

Here, I need to convert alphanumeric String to byte value ,for example:

String str ="1b" to byte value.I tried by using getbytes,(Byte.valueOf(str)), (Byte.parseByte(str)).

All the commands showed an exception called

  java.lang.NumberFormatException

help please

Community
  • 1
  • 1
user1939336
  • 31
  • 2
  • 7

3 Answers3

3

Assuming you're always going to have a 2-character string representing a hex value, you just want:

byte b = Byte.parseByte(text, 16);

You need to specify the 16 so that it knows to treat it as hex.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • what if it is a 3-character string? – user1939336 Dec 31 '12 at 09:35
  • @user1939336: Then it doesn't represent a single byte in hex, does it? – Jon Skeet Dec 31 '12 at 09:53
  • I need to convert alphanumeric string of 3-character to a byte ,then what i have to do for that? – user1939336 Dec 31 '12 at 09:57
  • 1
    @user1939336: It's impossible to answer that without knowing what value you'd want. What byte value should "XYZ" give? Once you've decided the behaviour you want, the implementation should be easy - but until you've decided that, it's impossible to help you. – Jon Skeet Dec 31 '12 at 12:36
2

i hope this may help you

public class TestByte
{    
    public static void main(String[] argv) {

            String example = "example100";
            byte[] bytes = example.getBytes();

            System.out.println("Text : " + example);
            System.out.println("Text [Byte Format] : " + bytes);


    }
}
Mr.Cool
  • 1,525
  • 10
  • 32
  • 51
1

using

Byte.parseByte("0x0b", 16); 16:radix

Daniel
  • 79
  • 3