tags:

views:

222

answers:

3

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

+2  A: 

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))
michael.kebe
+6  A: 

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)
Ben Lings
+5  A: 

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

Arjan Blokzijl