1

I have a hex code in string example

String a="0x52";

I want to store this hex value in a byte example

byte b=(do something with a so i can store it in b);

so byte b is going to store 0x52

How to achieve this ?

Just for reference my teacher gave this sample code

public  byte[] CONSIGNMENT_0 = { 0x52, 0x44, 0x54, 0x30, 0x31, 0x9, 0x6f, 0x6e,  
                                           0x65, 0xa, 0x32, 0x9, 0x74, 0x77, 0xa, 0xd };

And its working perfectly so we can store 0x52 in a byte variable.

1
  • I tried that its not working its giving a run time error NumberFormatException: for input string "0x52" even Byte.parseByte is not working Commented May 13, 2017 at 15:58

1 Answer 1

1

You are writing a hex constant, so you can parse it with Integer.parseInt(String, int) (the second argument is a base) and then cast it to a byte. Like,

String a = "0x52";
byte b1 = 0x52;
byte b2 = (byte) Integer.parseInt(a.substring(2), 16);
System.out.println(b1 == b2);

Outputs

true
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.