3

What is the best way to read and write C-styled byte stuctures in Scala, like this:

    struct account {
            int id;
            char[10] data1;
            char[10] data2;
            float dataFloat;
    };

There's unpack function in Python, to interpret strings as packed binary data. But I can't find any analogue in Scala.

What is standart way for such a mapping in Scala? Read bytes one by one is very unsufficiant. The protocol I need to parse comes back fromk 1980s and contains different fields (short, int, float) so read it byte-by-byte will be very unsufficient.

oluies
  • 17,694
  • 14
  • 74
  • 117
Alexander Teut
  • 323
  • 1
  • 3
  • 14

2 Answers2

5

http://scodec.org/ (code) might be what you want. Some examples in this video: Introduction to Shapeless with applications from scodec

Example from the docs: Automatic case class binding is supported via Shapeless HLists:

case class Point(x: Int, y: Int, z: Int)

val pointCodec = (int8 :: int8 :: int8).as[Point]

val encoded: Attempt[BitVector] = pointCodec.encode(Point(-5, 10, 1))
// Successful(BitVector(24 bits, 0xfb0a01))

val decoded: Attempt[DecodeResult[Point]] = pointCodec.decode(hex"0xfb0a01".bits)
// Successful(DecodeResult(Point(-5,10,1),BitVector(empty)))
oluies
  • 17,694
  • 14
  • 74
  • 117
1

As Scala can still rely on the java classes :

You are of course using an InputStream to read the bytes, Converting the byte[] to a string should be the same as Java using new String(byte[]).

Converting the float is another problem answered in this SO question about byte to float conversion in Java.

An easier way would be to use the java.nio.ByteBuffer which has a convenient getFloat method

Community
  • 1
  • 1
dvhh
  • 4,724
  • 27
  • 33