954,529 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

parse string to byte in J2ME

Hi all,

I am stucked at this problem - net to let user set string as byte eg. "0xFF", And parse it to byte. Problem is, that using...

byte byteVar = (byte) "0xFF";

...is incompatible. Nice page about this is there .

Any idea how solve this? Thx for your help..

RossR
Newbie Poster
7 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
 

In Jave SE the Byte class has a constructor that takes a String as parameter:

byte byteVar = new Byte("0xFF");


I don't know if ME will do that unboxing, so maybe

byte byteVar = (new Byte("0xFF")).byteValue() ;
JamesCherrill
Posting Genius
Moderator
6,372 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

You can also use

Byte.parseByte("0xFF")


method to parse String into Byte , I generally use this way to convert string into any other data type

e.g. from String to Integer

Integer.parseInt("123")
javinpaul
Newbie Poster
20 posts since Oct 2010
Reputation Points: 4
Solved Threads: 6
 

Thx for your reply. Unfortunately I tried using "parse" but ...wrote little "B" oops :]... And prefix "0x" can not be used. So this is working without any error:

byte testByte = Byte.parseByte("c3");


But despite that my implemetation was not working. After a while of testing I find out that problem must somewhere in parsing. This works...

byte testByte1 = (byte)0xc3;


But not this:

byte testByte2 = Byte.parseByte("c3");


... i don't understand, maybe there is problem with hexadecimal number. So i try:

byte testByte2 = Byte.parseByte("c3", 16);


...but still nothing :(EDIT:

Clue:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5015891 [/B]

RossR
Newbie Poster
7 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
 

Hi Ross,

byte testByte2 = Byte.parseByte("c3");

This will not work it will give you
Exception in thread "main" java.lang.NumberFormatException: For input string: "c3"
because this version of parseByte() accept value in decimal so only digits are applicable.

byte testByte2 = Byte.parseByte("c3", 16);

This is correct way of using this method if you are parsing Hexa decimal number but again "c3" is out of byte's range its decimal value is "195" while byte can only accept upto 127.

hope this helps.

Thanks
Javin

javinpaul
Newbie Poster
20 posts since Oct 2010
Reputation Points: 4
Solved Threads: 6
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: