Let's say I have the string "1e". In Java, how can I convert it to the byte 0x1e?
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
2009-09-23 16:12:45
How would you distinguish a byte of value 30 and 0x1e, which are stored identically when of type byte?
Kathy Van Stone
2009-09-23 16:22:01
@phpscriptcoder: No, you would get 1e. Try this: String roundtrip = Integer.toHexString(Integer.parseInt(str, 16));
erickson
2009-09-23 16:24:38
+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
2009-09-23 16:17:00
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.
2010-05-28 16:31:41
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
2009-09-24 20:58:27
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
2009-09-24 21:11:27