Mapping C Structures in Scala
What is the best way to read and write string bytes in Scala style, e.g .:
struct account {
int id;
char[10] data1;
char[10] data2;
float dataFloat;
};
There's an unpacking function in Python to interpret strings as packed binary data. But I cannot find an analogue in Scala.
What is the standard way for such a display in Scala? Reading bytes one by one is very inconvenient. The protocol I need for parsing comes back from the 1980s and contains different fields (short, int, float), so reading its byte value would be very unsatisfactory.
source to share
http://scodec.org/ (code) might be what you want. Some examples in this video: Introduction to seamless with apps 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)))
source to share
As Scala can still rely on java classes:
You are of course using InputStream
to read bytes, Convert string byte[]
to string should be the same as Java using new String(byte[])
.
The float conversion is another issue that was answered in this SO question about byte for floating point conversion in Java .
An easier way is to use java.nio.ByteBuffer which has a convenient getFloat method
source to share