简体   繁体   English

获取UnsafePointer <UInt8> 将Int写入流中

[英]Get UnsafePointer<UInt8> to Int to write an encoded Int to a stream

How do you get a pointer to a number variable? 如何获得指向数字变量的指针? Eg convert get an UnsafePointer<UInt8> that points to the storage containing a Swift Int . 例如,转换将获得一个UnsafePointer<UInt8> ,它指向包含Swift Int的存储。 I need to write the Int to a stream. 我需要将Int写入流中。

My example: 我的例子:

public static func writeToOutputStream(text: String!, outputStream:NSOutputStream!){
    let encodedDataArray = [UInt8](text.utf8)
    //send length of the data so the server knows when the message ends.
    outputStream.write(encodedDataArray.count, maxLength: 4)
    outputStream.write(encodedDataArray, maxLength: encodedDataArray.count)
}

I need encodedDataArray.count to be an UnsafePointer<UInt8> if I want to send the data length too. 如果我也想发送数据长度,我需要encodedDataArray.countUnsafePointer<UInt8>

Use withUnsafePointer , like this: withUnsafePointer使用,如下所示:

let outputStream = NSOutputStream(toMemory: ())
outputStream.open()

var count: Int = 0x01020304 // = encodedDataArray.count in your program
withUnsafePointer(&count) { (pointer: UnsafePointer<Int>) -> Void in
    outputStream.write(UnsafePointer<UInt8>(pointer), maxLength: 4)
}

outputStream.propertyForKey(NSStreamDataWrittenToMemoryStreamKey)

Result: 结果:

<04030201>

Note that it'll write the bytes in little-endian order (because all platforms on which Swift currently runs are little-endian). 请注意,它将以低字节序写入字节(因为当前运行Swift的所有平台都是低字节序)。 If you want to write in big-endian, use encodedDataArray.count.bigEndian . 如果要使用big-endian编写,请使用encodedDataArray.count.bigEndian

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 整数不能转换为UInt8吗? - Int not convertible to UInt8? “UnsafePointer <UInt8> &#39;不能转换为&#39;UnsafePointer &lt;_&gt;&#39; - 'UnsafePointer<UInt8>' is not convertible to 'UnsafePointer<_>' 不安全指针<UInt8> Swift 3 中的初始化程序 - UnsafePointer<UInt8> initializer in Swift 3 如何快速将 Int8 转换为 Uint8? - how to convert Int8 to Uint8 in swift? UnsafePointer 的问题<Uint8>在 Swift 的 SQLite 项目中 - Issue with UnsafePointer<Uint8> in SQLite project in Swift swift 3 iOS:将UInt8数组转换为int8 - swift 3 ios : convert UInt8 Array to int8 二进制运算符+ =不能应用于类型&#39;UnsafeMutablePointer的操作数 <UInt8> &#39; 和&#39;Int&#39; - binary operator += cannot be applied to operands of type 'UnsafeMutablePointer<UInt8>?' and 'Int' Uint8不能转换为Int(节省游戏最佳时间) - Uint8 is not convertible to Int ( saving a game best time ) 将Int [int8]的带符号数组快速转换为Int [UInt8]的无符号数组 - Swift converting signed array of Int [int8] to unsigned array of Int [UInt8] 无法使用类型为&#39;(UInt32,UnsafePointer的参数列表&#39;调用&#39;CCHmac&#39; <Int8> ,UInt,[CChar],Int,UnsafeMutablePointer <CUnsignedChar> ) - Cannot invoke 'CCHmac' with an argument list of type '(UInt32, UnsafePointer<Int8>, UInt, [CChar], Int, UnsafeMutablePointer<CUnsignedChar>)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM