Trimming byte array when converting byte array to string in Java/Scala

Posted by prosseek on Stack Overflow See other posts from Stack Overflow or by prosseek
Published on 2014-06-01T02:43:09Z Indexed on 2014/06/01 3:26 UTC
Read the original article Hit count: 152

Filed under:
|
|
|

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))
}

© Stack Overflow or respective owner

Related posts about java

Related posts about string