1

I'm writing a little program in android and in it I've a list of byte values in a string variable. something like this :

String src = "255216173005050";

Now, what i need to do is to extract the byte values from the source string and store them in a byte variables. (in above source string, i'll have 5 bytes to store)

For doing this i could successfully read source string and separate the byte values by 3 characters. (255, 216, 173, 005, 050)

The problem is that i failed to convert these strings to their byte values.

it is what I've already done :

String str = "255";
byte b = (byte) Integer.parseInt(str);

By running this, b will be -60 ! Is there Please help me !

1

3 Answers 3

0

When you write

byte b = (byte) Integer.parseInt(str);

you will get a signed byte. If you look at your int that is discarded using something like

int i = Integer.parseInt(str);
System.out.println(i);
byte b = (byte) i;

you will probably see that i contains the value you want.

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

Comments

0

This should work. Then just access various indices of the byte array to get the individual pieces. If your text is an abnormal character set - then pass the character set into the getBytes() method.

byte[] bytes = src.getBytes();

2 Comments

Locale will byte him hard. Besides, it wouldn't get close to what he's sort of asking... "255".getBytes() != 0xFF
Paul, Thanks for reply .. but actually by running your code, it will convert "2", "5", "5" to separated byte values .. my question is how to convert "255" to the byte ..
0

Don't use parseInt when you want a byte; instead try Byte.parseByte. Also note that bytes have a range of -128 to 127 (inclusive).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.