0

We need to implement a binary protocol using the Swift programming language for Apple apps. We need to pack bytes, shorts, long and doubles into a binary string but it doesn't seem like the Swift language is capable of doing this. So I would just like to confirm if this is the case?

Basically we want to convert the following Java code to Swift code:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(123);
dos.writeByte(123);
dos.writeShort(123);
dos.writeDouble(1.23);
dos.writeFloat(1.23f);
dos.flush();
byte[] binaryData = baos.toByteArray();

// Send the binaryData somewhere! ->>>

It doesn't seem like this is possible using Swift. If so what are the alternatives to work around this issue?

Steven
  • 69
  • 5
  • 2
    Possibly helpful: https://stackoverflow.com/q/38023838/1187415, https://stackoverflow.com/q/43241845/1187415, https://stackoverflow.com/q/47525922/1187415 – Martin R Jun 13 '22 at 11:27
  • Be careful reading binary directly into Swift structs or classes. Structs at least use C style memory layout which have alignment requirements on properties, but unlike most C implementations there isn’t a compiler directive to specify they should be packed instead – Chip Jarred Jun 14 '22 at 08:29
  • Thank you @MartinR for the links to the other questions. This will help with reading binary data into Longs, Doubles and ints. But we need to also write these types to binary, do you know of any other places where there is examples of creating binary data from ints, longs and doubles? It's one of the few cases where google comes up empty! – Steven Jun 14 '22 at 13:40
  • Perhaps have a look at ByteBuffer of the SwiftNIO project: https://github.com/apple/swift-nio, https://apple.github.io/swift-nio/docs/current/NIOCore/Structs/ByteBuffer.html. – That may be what you are looking for. – Martin R Jun 15 '22 at 06:37

0 Answers0