Using ByteBuffer, I can convert a string to an array of bytes:
val x = ByteBuffer.allocate(10).put("Hello".getBytes()).array()
> Array[Byte] = Array(104, 101, 108, 108, 111, 0, 0, 0, 0, 0)
When converting an array of bytes to a string, I can use new String(x). However, the string becomes hello?????, and I need to trim the byte array before converting it to a string. How can i do this?
I use this code to trim zeros, but I'm wondering if there is an easier 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))
}
source
share