Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

objective c - How to write Int32 to NSOutputStream in Swift

I'm trying to write an Int32 to an NSOutputStream in Swift and I'm having difficulties. In ObjC, I would have done something like this:

-(void)write4ByteField:(int32_t)value {
    [stream write:((value >> 24) & 0xff)];
    [stream write:((value >> 16) & 0xff)];
    [stream write:((value >> 8) & 0xff)];
    [stream write:(value & 0xff)];
}

However, in Swift, it really doesn't like me doing all of that low-level bit-shifting and I gave up on casting the values all over the place.

I tried something like:

func write4ByteField(value: Int32) {
    stream.write(&value, maxLength: sizeof(Int32))
}

but I get an error int16 is not convertible to @lvalue inout $T4

Similarly, if I try to go to NSData I get the same error:

func write4ByteField(value: Int32) {
    let data = NSData(bytes: &value, length: sizeof(Int32)
    stream.write(data.bytes, maxLength: sizeof(Int32))
}

Any suggestions? I'm guessing I am just going about this the wrong way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your last approach is almost correct. value needs to be a variable parameter so that you can use it as "in-out expression" &value, and data.bytes needs a cast:

func write4ByteField(var value: Int32) {
    let data = NSData(bytes: &value, length: sizeof(Int32))
    stream.write(UnsafePointer(data.bytes), maxLength: sizeof(Int32))
}

It can also be done without NSData, including the conversion to big-endian byte order:

func write4ByteField(value: Int32) {
    var valueBE = value.bigEndian
    withUnsafePointer(&valueBE) { 
        self.stream.write(UnsafePointer($0), maxLength: sizeofValue(valueBE))
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...