0

I've been messing around with MIDI files in swift. After converting the file to a string with

        for byte in readFile {
            let hex = String(format: "%02x", UInt(byte))
            hexString.append(contentsOf: hex)
        }

But now I've made the modifications to the hex string I need to write it back to a new MIDI file with the correct encoding. I'm assuming I need to use something like:

hexString.write(to: opUrl, atomically: false, encoding: String.Encoding.utf8)

But the encoding is obviously wrong. I'm a bit confused in this area so any help would much be much appreciated. Also if anyone can give an idiot proof explanation of the atomically: option that would be a bonus!

Chris Barrett
  • 571
  • 4
  • 23
  • 2
    I don’t get why you converted the data in this odd way (“hex string”). Why not read the file as Data? – matt Apr 17 '19 at 10:21
  • Same explaination as here: https://stackoverflow.com/questions/50030468/swxmlhash-parse-data-object/50031363#50031363 In your case, you want Data. Why use "Hex representation String" if it's a Binary file. Just save `(NS)Data` and read it as such. – Larme Apr 17 '19 at 10:24
  • @matt I suspected it was a bit of a weird way around but I'm a complete noob to swift. I basically just need to search for a series of values in the file and extract some data after that point. This seemed like the easiest way but any pointers would be greatly appreciated – Chris Barrett Apr 17 '19 at 10:24
  • Well that is just the sort of thing Data lets you do. – matt Apr 17 '19 at 10:25

1 Answers1

0

After converting the file to a string

Well don’t convert the file to a string. Use the Data struct. Read the file as Data. Examine it as Data. Manipulate it as Data. Save it as Data.

https://developer.apple.com/documentation/foundation/data

matt
  • 515,959
  • 87
  • 875
  • 1,141