似乎我发现使用java ByteBuffer
的行为非常奇怪。我的目的是填写ByteBuffer
并使用compareTo
方法。我使用Ubuntu在OpenJDK 64bit上运行。代码片段是scala工作表,但在java类中它的行为相同。
这很好用:
import java.nio.{ByteOrder, ByteBuffer}
import org.apache.commons.codec.binary.Hex
val str1 = "FFFFFFFFFFF000000000000000000000"
val str2 = "FFFFFFFFFFFF00000000000000000000"
val bb1 = ByteBuffer.wrap(Hex.decodeHex(str1.toCharArray))
val bb2 = ByteBuffer.wrap(Hex.decodeHex(str2.toCharArray))
println(
s"""
|bb1 hex: ${new String(Hex.encodeHex(bb1.array()))}
|bb2 hex: ${new String(Hex.encodeHex(bb2.array()))}
|Comparing: bb1.compareTo(bb2): ${ bb1.compareTo(bb2)}
""".stripMargin)
bb1 hex: fffffffffff000000000000000000000
bb2 hex: ffffffffffff00000000000000000000
Comparing: bb1.compareTo(bb2): -15
这不起作用(并且不知道为什么)
import java.nio.{ByteOrder, ByteBuffer}
import org.apache.commons.codec.binary.Hex
val str1 = "FFFFFFFFFFF000000000000000000000"
val str2 = "FFFFFFFFFFFF00000000000000000000"
val bb1 = ByteBuffer.allocate(16)
val bb2 = ByteBuffer.allocate(16)
bb1.put(Hex.decodeHex(str1.toCharArray))//Do the same like in wrap
bb2.put(Hex.decodeHex(str2.toCharArray))//Do the same like in wrap
println(
s"""
|bb1 hex: ${new String(Hex.encodeHex(bb1.array()))}
|bb2 hex: ${new String(Hex.encodeHex(bb2.array()))}
|Comparing: bb1.compareTo(bb2): ${ bb1.compareTo(bb2)}
""".stripMargin)
bb1 hex: fffffffffff000000000000000000000
bb2 hex: ffffffffffff00000000000000000000
Comparing: bb1.compareTo(bb2): 0
答案 0 :(得分:1)
啊,这是另一个java"功能",有时会让你想打屁股,提出它并认为这是个好主意:)
ByteBuffer
具有当前位置的概念,因此当您调用put
两次时,第二个数组的内容将在第一个数组结束后追加。有趣的是compareTo
比较了从各个当前位置开始的两个缓冲区的内容。因此,在您的情况下,两个序列都是空的,它只返回0.