Converting strings into little endian bytes in Swift?

368 Views Asked by At

Perhaps I'm a little too new to understanding little endian, but I am trying to achieve a task that seems to be confusing me. I am working with point clouds in my iOS app, and am trying to pragmatically create a PLY file for export. The app is functioning as expected, creating the PLY file, and saving it accordingly. However, I've found that the sheer amount of data being written to the file could be saved more efficiently, and it was suggested to consider saving in a little endian format.

This is my current implementation. All of the values are currently Floats;

private func writeToPly() {
    
    var fileToWrite = ""
    let headers = ["ply", "format ascii 1.0", "element vertex \(currentPointCount)", "property float x", "property float y", "property float z", "property uchar red", "property uchar green", "property uchar blue", "property uchar alpha", "element face 0", "property list uchar int vertex_indices", "end_header"]
    for header in headers {
        fileToWrite += header
        fileToWrite += "\r\n"
    }
    
    for i in 0..<currentPointCount {
        let point = particlesBuffer[i]
        let colors = point.color
        let red = colors.x * 255.0
        let green = colors.y * 255.0
        let blue = colors.z * 255.0
        let pvValue = "\(point.position.x) \(point.position.y) \(point.position.z) \(Int(red)) \(Int(green)) \(Int(blue)) 255"
        fileToWrite += pvValue
        fileToWrite += "\r\n"
    }

    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    let file = documentsDirectory.appendingPathComponent("ply_\(UUID().uuidString).ply")
    
    do {
        try fileToWrite.write(to: file, atomically: true, encoding: String.Encoding.ascii)
        self.fileWriteSubject.send(file)
    } catch {
        print("Failed to write PLY file", error)
    }
}

Besides changing the headers variable to indicate that the file would be format binary_little_endian 1.0, I believe I need to look at the for in in 0..<currentPointCount loop, and determine how I could convert the lines into little endian format, then write them to the PLY file (though I'm not sure if I have that idea right).

0

There are 0 best solutions below