I'm specifically interested in Scala (2.8) techniques for building strings with formats as well as interesting ways to make such a capability easily accessible where it's useful (lists of bytes, String, ...?)..
public class Hex {
public static String valueOf (final byte buf[]) {
if (null == buf) {
return null;
}
final StringBuilder sb = new StringBuilder(buf.length * 2);
for (final byte b : buf) {
sb.append(String.format("%02X", b & 0xff));
}
return sb.toString();
}
public static String valueOf (final Byteable o) {
return valueOf(o.toByteArray());
}
}
This is only a learning exercise (so the utility and implementation of the Java isn't a concern.)
Thanks
To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st .
To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.
In Scala, Byte is a 8-bit signed integer (equivalent to Java's byte primitive type). The method ^(x:Byte) method is utilized to return the bitwise XOR of this value and x. Method Definition: Byte ^(x: Byte): Int. Return Type: It returns return the bitwise XOR of this value and x.
String str = new String(byteArray, StandardCharsets. UTF_8); String class also has a method to convert a subset of the byte array to String. byte[] byteArray1 = { 80, 65, 78, 75, 65, 74 }; String str = new String(byteArray1, 0, 3, StandardCharsets.
This doesn't handle null
in the same way as your code.
object Hex {
def valueOf(buf: Array[Byte]): String = buf.map("%02X" format _).mkString
def valueOf(o: Byteable): String = valueOf(o.toByteArray)
}
If you want to be able to handle possibly-null
arrays, you might be better doing that from calling code and doing:
val bytes: Array[Byte] = // something, possibly null
val string: Option[String] = Option(bytes).map(Hex.valueOf)
Perhaps there are more elegant ways, but something like:
def valueOf(bytes : List[Byte]) = bytes.map{
b => String.format("%02X", new java.lang.Integer(b & 0xff))
}.mkString
should work.
You should use Scala's Option
type instead of null
. (This is tested with Scala 2.8.0.RC1)
object Hex {
def valueOf (buf: Array[Byte]) = {
if (null == buf) {
None
} else {
val sb = new StringBuilder(buf.length * 2)
for (b <- buf) {
sb.append("%02X".format(b & 0xff))
}
Some(sb.toString())
}
}
/*
def valueOf(o: Byteable) = {
return valueOf(o.toByteArray());
}
*/
}
println(Hex.valueOf(Array(-3, -2, -1, 0, 1, 2, 3)))
println(Hex.valueOf(null))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With