Tony Morris
Java Q&A (FAQ, Trivia)
Originally posted by Norm Radder:
To use bytes as unsigned small ints, AND them with 0xFF after they have been promoted to an int to strip the h.o. sign bits.
To get leading 0's append digits to "0000000" and use substring to pickup rightmost n chars.
Originally posted by Layne Lund:
Thanks for the code. I like how your method uses the Iterable interface so that it isn't limited to just arrays. I understand how to iterate over the array. My question was primarily concerned with issues converting each individual byte.
The code above still doesn't solve the second problem. Say for example, one of the bytes in the array is -1. Integer.toHexString() will return "ffffff" instead of just "ff". (In fact, your solution will append "0ffffffff" since the hex.length() is not 1.) Similar issues will arise with any negative number which means the resulting String will have more than two characters for each byte. I guess I can just use substring() to get the last two bytes, but as I said earlier, that seems like an ugly solution to me. Maybe I'm just too paranoid about writing elegant code
Layne
Tony Morris
Java Q&A (FAQ, Trivia)
"I'm not back." - Bill Harding, Twister
Originally posted by Jim Yingst:
JDK 5 does offer other alternatives too, such as:
Originally posted by Norm Radder:
> Integer.toHexString() returns a String with too many characters (8 instead
of 2
If a byte(being signed has its h.o. bit set when it is converted to an int, the sign will spread thru the h.o. bits of the int. Using toHexString() will then output 0xFFFFFFFF. I assume what you want to see is 0XFF
To treat a byte as unsigned, ie prevent the spread of 1 bits, AND it with 0xFF.
Output is: fa
Grow a forest with seedballs and this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
|