首页 文章

在Scala中映射C结构

提问于
浏览
3

在Scala中读取和编写C风格字节结构的最佳方法是什么,如下所示:

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

Python中有解包函数,将字符串解释为压缩二进制数据 . 但我在Scala中找不到任何类比 .

在Scala中进行这种映射的标准方法是什么?逐个读取字节非常不合适 . 我需要解析的协议从20世纪80年代开始,包含不同的字段(short,int,float),因此逐字节读取它将是非常低效的 .

2 回答

  • 1

    http://scodec.org/ (code)可能是你想要的 . 此视频中的一些示例:Introduction to Shapeless with applications from scodec

    文档示例:通过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)))
    
  • 5

    由于Scala仍然可以依赖java类:

    您当然使用 InputStream 来读取字节,将 byte[] 转换为字符串应该与使用 new String(byte[]) 的Java相同 .

    转换浮动是另一个问题in this SO question about byte to float conversion in Java .

    更简单的方法是使用java.nio.ByteBuffer,它有一个方便的getFloat方法

相关问题