Using ByteBuffer, I can convert a string into byte array:
val x = ByteBuffer.allocate(10).put("Hello".getBytes()).array()
> Array[Byte] = Array(104, 101, 108, 108, 111, 0, 0, 0, 0, 0)
When converting the byte array into string, I can use new String(x)
.
However, the string becomes hello?????
, and I need to trim down the byte array before converting it into string. How can I do that?
I use this code to trim down the zeros, but I wonder if there is simpler way.
def byteArrayToString(x: Array[Byte]) = {
val loc = x.indexOf(0)
if (-1 == loc)
new String(x)
else if (0 == loc)
""
else
new String(x.slice(0,loc))
}
Assuming that 0: Byte
is a trailing value, then
implicit class RichToString(val x: java.nio.ByteBuffer) extends AnyVal {
def byteArrayToString() = new String( x.array.takeWhile(_ != 0), "UTF-8" )
}
Hence for
val x = ByteBuffer.allocate(10).put("Hello".getBytes())
x.byteArrayToString
res: String = Hello
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With