1

I have a data structure java.nio.HeapByteBuffer[pos=71098 lim=71102 cap=94870], which I need to convert into Int (in Scala), the conversion might look simple but whatever which I approach , i did not get right conversion. could you please help me?

Here is my code snippet:

val v : ByteBuffer= map.get("company").get
val utf_str = new String(v, java.nio.charset.StandardCharsets.UTF_8)
println (utf_str)

the output is just "R" ??

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
user1622127
  • 41
  • 1
  • 1
  • 6
  • 1
    How is the integer encoded? Is it a 4 byte UTF-8 encoded string or a 4 byte int value? Are you expecting big endian or little endian? Can you show us the code which write the value. – Peter Lawrey Oct 31 '14 at 14:18
  • And do you want an Int, or a String? Subject and code say String, question says "convert into Int". – The Archetypal Paul Oct 31 '14 at 15:39

1 Answers1

2

I can't see how you can even get that to compile, String has constructors that accepts another string or possibly an array, but not a ByteBuffer or any of its parents.

To work with the nio buffer api you first write to a buffer, then do a flip before you read from the buffer, there are lots of good resources online about that. This one for example: http://tutorials.jenkov.com/java-nio/buffers.html

How to read that as a string entirely depends on how the characters are encoded inside the buffer, if they are two bytes per character (as strings are in Java/the JVM) you can convert your buffer to a character buffer by using asCharBuffer.

So, for example:

val byteBuffer = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN);
byteBuffer.putChar('H').putChar('i').putChar('!')
byteBuffer.flip()
val charBuffer = byteBuffer.asCharBuffer
assert(charBuffer.toString == "Hi!")
johanandren
  • 11,249
  • 1
  • 25
  • 30