I am trying to parse a binary file in swift, and although everything works for me, I have a situation where I have variable fields.
I have all my parsing working in the default case
I grab
1-bit field 1-bit field 1-bit field 11-bits field 1-bit field (optional) 4-bit field (optional) 4-bit field 1-bit field 2-bit field (optional) 4-bit field 5-bit field 6-bit field (optional) 6-bit field (optional) 24-bit field (junk data - up until byte buffer 0 - 7 bits as needed)
Most data uses only a certain set of options, so I went ahead and started writing classes to process this data. My general approach is to create a pointer structure, and then build an array of bytes from this:
let rawData: NSMutableData = NSMutableData(data: input_nsdata) var ptr: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8(rawData.mutableBytes) bytes = UnsafeMutableBufferPointer<UInt8>(start: ptr, count: rawData.length - offset)
So, I am finishing work with the [UInt8] array, and I can do the parsing in the same way as:
let b1 = (bytes[3] & 0x01) << 5 let b2 = (bytes[4] & 0xF8) >> 3 return Int(b1 | b2)
Therefore, when I encounter problems, these are optional fields, because my data is not specifically related to byte boundaries, everything becomes more complicated. In an ideal world, I would probably just work directly with the pointer and advance it by bytes as needed, however, I donβt know how to advance the pointer to 3 bits, which brings me to my question.
What is the best approach to handle my situation?
One of the ideas that I thought was to create different structures reflecting optional fields, except that I'm not sure about the quick creation of bit-aligned packed structures.
What is my best approach here? For clarification, the initial 1-bit fields determine which of the optional fields are set.