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


using bytebuffer, can convert string 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 byte array string, can use new string(x). however, string becomes hello?????, , need trim down byte array before converting string. how can that?

i use code trim down zeros, wonder if there 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 0: byte 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 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -