0

I need to read from a UInt8 array and append certain bytes into a String but it gives me error no matter what I tried. += doesn't work with CChar(ptr[i]) it complains. String.append() doesn't work it expects Character and not CChar, and why in the hell everything is so convertible in Swift but not CChar to a Character? here's my sample func

func FromBuf(ptr: UnsafeMutablePointer<UInt8>, length len: Int) -> String {
  var i: Int = 0
  while (i < len) {
    if (i > 0) { s.append(CChar(ptr[i])) }
    i++
  }
  return s
}

Also, what would be the best way to set a String from a portion of a UInt8 array? I tried this but it doesn't work, var s = String(bytes: &ptr[3], encoding: NSASCIIStringEncoding). Actually this initialiser also lacks the way to specify how many bytes to get from the pointer.

1 Answer 1

1

You can use the Foundation method NSString(bytes:length:encoding:) to convert from raw bytes to a String.

import Foundation

func FromBuf(ptr: UnsafeMutablePointer<UInt8>, length len: Int) -> String? {
    // convert the bytes using the UTF8 encoding
    if let theString = NSString(bytes: ptr, length: len, encoding: NSUTF8StringEncoding) {
        return theString as String
    } else {
        return nil // the bytes aren't valid UTF8
    }
}

If you just want to use a portion of the byte array, then you could also supply the starting offset to the function as an additional parameter.

import Foundation

func FromBuf(ptr: UnsafeMutablePointer<UInt8>, startingOffset: Int, length len: Int) -> String? {
    // convert the bytes using the UTF8 encoding
    if let theString = NSString(bytes: ptr + startingOffset, length: len, encoding: NSUTF8StringEncoding) {
        return theString as String
    } else {
        return nil // the bytes aren't valid UTF8
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Marc, this even saved me from the append one char at a time thing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.