将数字(short、int、long、float、double、bigint)转换为字节数组:Scala/Java
converting numbers (short, int, long, float, double,bigint) to byte array: Scala/Java
我已经按照 scala 代码将 (short, int, long, float, double,bigint) 转换为字节数组。
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
}
}
这就够了吗?我是否需要在最后调用任何清理方法,例如 clear()
、mark()
、reset()
以确保没有 ByteBuffer 泄漏
当我使用 allocateDirect
方法时,它抛出以下异常。那么,这是否意味着 allocateDirect
方法没有支持数组?
Exception in thread "main" java.lang.UnsupportedOperationException
at java.nio.ByteBuffer.array(ByteBuffer.java:994)
- 是的,这就是所有需要的。没有对 nio 缓冲区进行清理。
- 确实,直接缓冲区没有后备数组。
我已经按照 scala 代码将 (short, int, long, float, double,bigint) 转换为字节数组。
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
}
}
这就够了吗?我是否需要在最后调用任何清理方法,例如
clear()
、mark()
、reset()
以确保没有 ByteBuffer 泄漏当我使用
allocateDirect
方法时,它抛出以下异常。那么,这是否意味着allocateDirect
方法没有支持数组?
Exception in thread "main" java.lang.UnsupportedOperationException at java.nio.ByteBuffer.array(ByteBuffer.java:994)
- 是的,这就是所有需要的。没有对 nio 缓冲区进行清理。
- 确实,直接缓冲区没有后备数组。