views:

387

answers:

3

Let's say I have the string "1e". In Java, how can I convert it to the byte 0x1e?

+8  A: 
Integer.parseInt(str, 16);
ZZ Coder
I tried that but that creates an int, not a byte--so for "1e" I would get 30, not 0x1e, even if I cast to a byte.
phpscriptcoder
How would you distinguish a byte of value 30 and 0x1e, which are stored identically when of type byte?
Kathy Van Stone
@phpscriptcoder: No, you would get 1e. Try this: String roundtrip = Integer.toHexString(Integer.parseInt(str, 16));
erickson
+8  A: 

Byte.parseByte will return a byte by parsing a string representation.

Using the method with the (String, int) signature, the radix can be specified as 16, so one can parse a hexadecimal representation of a byte:

Byte.parseByte("1e", 16);
coobird
Danger! This method will fail to parse negative byte values, for example, "AD". See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6259307 . Better to use Integer.parseInt
Dave L.
A: 

I got both of the methods to work. However, then I found out that this wasn't what I needed to do anyway...

phpscriptcoder
But the question you asked ***was*** answered appropriately and correctly. Please be sure to accept an answer to your question, regardless of if you've discovered your problem _wasn't_ the question you asked.
Brandon Belvin