什么是Scala方式来实现这个Java“byte [] to Hex”类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2756166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:29:42  来源:igfitidea点击:

What is/are the Scala way(s) to implement this Java "byte[] to Hex" class

javascala

提问by nicerobot

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, ...?)..

我对使用格式构建字符串的 Scala (2.8) 技术以及使这种功能在有用的地方(字节列表、字符串……?)轻松访问的有趣方法特别感兴趣。

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.)

这只是一个学习练习(所以 Java 的实用程序和实现不是问题。)

Thanks

谢谢

采纳答案by Ben Lings

This doesn't handle nullin the same way as your code.

null与您的代码的处理方式不同。

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-nullarrays, you might be better doing that from calling code and doing:

如果您希望能够处理可能的null数组,则最好通过调用代码并执行以下操作来做到这一点:

val bytes: Array[Byte] = // something, possibly null
val string: Option[String] = Option(bytes).map(Hex.valueOf)

回答by michael.kebe

You should use Scala's Optiontype instead of null. (This is tested with Scala 2.8.0.RC1)

您应该使用 Scala 的Option类型而不是null. (这是用 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))

回答by Arjan Blokzijl

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.

应该管用。