codehammer
codehammer

Reputation: 885

converting numbers (short, int, long, float, double,bigint) to byte array: Scala/Java

I've following scala code to convert (short, int, long, float, double,bigint) to byte array.

def getByteArray(value: Any, of_type: String) = {
    of_type match {
      case "short" => ByteBuffer.allocate(2).putShort(value.asInstanceOf[Short]).array()
      case "int" => ByteBuffer.allocate(4).putInt(value.asInstanceOf[Int]).array()
      case "long" => ByteBuffer.allocate(8).putLong(value.asInstanceOf[Long]).array()
      case "float" => ByteBuffer.allocate(4).putFloat(value.asInstanceOf[Float]).array()
      case "double" => ByteBuffer.allocate(8).putDouble(value.asInstanceOf[Double]).array()
      case "bigint" => BigInt(value.toString).toByteArray
    }
  }
  1. Is this all is needed ? Do I need to call any cleanup methods at the end such clear(), mark(), reset() to ensure there are no ByteBuffer leaks

  2. When I use allocateDirect methods, it throws below exception. So, does it mean allocateDirect method has no backing array ?

Exception in thread "main" java.lang.UnsupportedOperationException at java.nio.ByteBuffer.array(ByteBuffer.java:994)

Upvotes: 4

Views: 2221

Answers (1)

sjrd
sjrd

Reputation: 22085

  1. Yes, that is all that's needed. There is no cleanup to be done on nio Buffers.
  2. Indeed, direct buffers do not have a backing array.

Upvotes: 2

Related Questions