如何将Swift字符串转换为C字节数组并返回到Swift字符串

如何将Swift字符串转换为C字节数组并返回到Swift字符串,swift,unicode-string,Swift,Unicode String,我尝试将Swift字符串作为[UInt8]字节数组,然后从C代码返回相同的字节数组,并将其转换回原始Swift字符串。我试图保留unicode(因此在转换/操作中不会丢失)。我在decrypt函数的转换行上收到一个错误“无法将'String.Encoding'类型的值转换为预期的参数类型'UInt'。请提前感谢您的帮助 // function to encrypt a string with custom "C" code and encode the result into a hex

我尝试将Swift字符串作为[UInt8]字节数组,然后从C代码返回相同的字节数组,并将其转换回原始Swift字符串。我试图保留unicode(因此在转换/操作中不会丢失)。我在decrypt函数的转换行上收到一个错误“无法将'String.Encoding'类型的值转换为预期的参数类型'UInt'。请提前感谢您的帮助

    // function to encrypt a string with custom "C" code and encode the result into a hex string
func EncryptString( password: String, stringToEncrypt: String) ->String {

    var hexStr = ""

    // convert the String password into utf8 bytes
    let pw = password.data(using: String.Encoding.utf8, allowLossyConversion:false)
    var passwordBytes : [UInt8] = Array(pw!)

    // convert the string to encrypt into utf8 bytes
    let bytes = stringToEncrypt.data(using: String.Encoding.utf8, allowLossyConversion:false)
    var buf : [UInt8] = Array(bytes!)

    // encrypt the string to encrypt with the Unicode password (both are Unicode in Swift)
    encryptData(&passwordBytes, Int32(password.count), &buf, Int32(stringToEncrypt.count))

    // turn the now encrypted "stringToEncrypt" into two character hex values in a string
    for byte in buf {
        hexStr.append(String(format:"%2X", byte))
    }

    // return the encrypted hex encoded string to the caller...
    return hexStr
}


func DecryptString( password: String, hexStringToDecrypt: String) ->String {

    var decryptedStr = ""

    // convert the String password into utf8 bytes
    let pw = password.data(using: String.Encoding.utf8, allowLossyConversion:false)
    var passwordBytes : [UInt8] = Array(pw!)

    // convert the string to encrypt into utf8 bytes
    let bytes = hexStringToDecrypt.data(using: String.Encoding.utf8, allowLossyConversion:false)
    var buf : [UInt8] = Array(bytes!)

    // encrypt the string to encrypt with the Unicode password (both are Unicode in Swift)

    let bytecount = password.count
    decryptData(&passwordBytes, Int32(password.count), &buf, Int32(hexStringToDecrypt.count))
            // turn the now encrypted "hexStringToDecrypt" into int values here is where I get error: Cannot convert value of type 'String.Encoding' to expected argument type 'UInt'
    var unicode_str = NSString(bytes: buf, length: bytecount, encoding: NSUTF32LittleEndianStringEncoding)

    // return the encrypted hex encoded string to the caller...
    return unicode_str
}

}

对于Swift 3/4,最好使用
数据类型来代替
UInt8

字符串
转换为
数据

let dat = string.data(using:.utf8)
数据
转换为
字符串

let str = String(data:dat, encoding:.utf8)
这里是使用
数据
代替
UInt8
进行加密的示例,这不是生产代码,至少缺少错误处理

func aesCBCEncrypt(data:Data, keyData:Data, ivData:Data) -> Data {
        let cryptLength = size_t(kCCBlockSizeAES128 + data.count + kCCBlockSizeAES128)
        var cryptData = Data(count:cryptLength)
        var numBytesEncrypted :size_t = 0

        let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in
            data.withUnsafeBytes {dataBytes in
                keyData.withUnsafeBytes {keyBytes in
                    ivData.withUnsafeBytes {ivBytes in
                        CCCrypt(CCOperation(kCCEncrypt),
                                CCAlgorithm(kCCAlgorithmAES),
                                CCOptions(kCCOptionPKCS7Padding),
                                keyBytes, keyData.count,
                                ivBytes,
                                dataBytes, data.count,
                                cryptBytes, cryptLength,
                                &numBytesEncrypted)
                    }}}}

    cryptData.count = (cryptStatus == kCCSuccess) ? numBytesEncrypted : 0

    return cryptData;
}

指出导致错误的确切行。您有几行正在尝试使用
utf8
。请确认您使用的是Swift 3或更高版本。谢谢!我使用的是Swift 4,当前出现错误的代码行是:var unicode\u str=NSString(字节:buf,长度:bytecount,编码:nsutf32littleendianstringcoding)你认为“C字节数组”到底是什么?据我所知,一个字节没有语言关联,它只是8位(现在)。Swift“C”也不是“。使用Swift 3/4时,最好使用
数据
类型代替
UInt8
。此外,
NSUTF32LittleEndianStringEncoding
不是将数据转换为字符串类型的正确方法,您需要指定字节的编码类型,即
utf8
,因为数据就是这样创建的。感谢所有帮助我解决此问题的人!rmaddy的答案(现在删除了?!)实际上对我的问题最有帮助。我只是需要按如下方式进行强制转换:让unicode_str=NSString(字节:buf,长度:hexStringToDecrypt.count/2,编码:String.encoding.utf8.rawValue)请放回您原来的post-rmaddy!我真的很感谢你的帮助!也非常感谢扎夫!非常感谢您的帮助!:-)