Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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))
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...