Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read a null terminated String from Data?

An iOS/Swift library delivers a Data object containing a null terminated string.
When converting it to a String by calling String(data: dataInstance, encoding: .utf8), the returned String ends with "\0".
Question now is, how do you convert the Data instance to a String without having "\0" appended? I.e. how can you omit the null terminating character at the end?

Trying to just .trimmingCharacters(in: .whitespacesAndNewlines) doesn’t have any effect, so your advise is very much appreciated. Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A possible solution: Determine the index of the terminating zero, and convert only the preceding part of the data:

let data = Data([65, 66, 0, 67, 0])
let end = data.firstIndex(where: { $0 == 0 }) ?? data.endIndex
if let string = String(data: data[..<end], encoding:.utf8) {
    print(string.debugDescription) // "AB"
}

If the data does not contain a null byte then everything will be converted.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading