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 !

Ahmad
  • 69,608
  • 17
  • 111
  • 137
atari83
  • 489
  • 1
  • 5
  • 15

3 Answers3

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();
RutledgePaulV
  • 2,568
  • 3
  • 24
  • 47
  • 1
    Locale will byte him hard. Besides, it wouldn't get close to what he's sort of asking... `"255".getBytes() != 0xFF` – Shark Jun 24 '13 at 14:19
  • 1
    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 .. – atari83 Jun 24 '13 at 14:23
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).

arshajii
  • 127,459
  • 24
  • 238
  • 287
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.

gobernador
  • 5,659
  • 3
  • 32
  • 51