Swift将字节数组转换为整数 [英] Swift converting a byte array to integers

查看:191
本文介绍了Swift将字节数组转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我是swift的新手,想将一个字节数组转换为几个整数。我已经用Java编写了工作代码,但我不太清楚如何将其转换为swift

Hello I am new to swift and would like to convert a byte array to several integers. I have written working code in Java but I am not quite sure how to take it to swift

byte[] codeData = Base64.decode(codeDataBase64, 0);
    ByteArrayInputStream bais = new ByteArrayInputStream(codeData);
    DataInputStream dis = new DataInputStream(bais);

    byte version = dis.readByte();
    if (version == 1) {
        int anID = dis.readInt();
        int anotherID = dis.readInt();
        byte[] TK = new byte[512];
        int readTK = dis.read(TK);
        if (readTK == TK.length) {
            Log.e("photoConnect success", "anID=" + anID + ", anotherID=" + anotherID + ", TK.length=" + TK.length);

这是我迄今为止在Swift中所拥有的:

Here is what I have in Swift thus far:

func base64ToByteArray(base64String: String) -> [UInt8]? {
    if let nsdata = NSData(base64Encoded: base64String) {
        var bytes = [UInt8](repeating: 0, count: nsdata.length)
        nsdata.getBytes(&bytes, length: nsdata.length)
        return bytes
    }
    return nil // Invalid input
}

这个函数将它带到一个字节数组但是我不确定使用什么Swift类来模仿Java中DataInputStream的行为。

This function takes it to an array of bytes but I am not sure what Swift class to use to mimic the behavior of DataInputStream in Java.

推荐答案

好的,我有一个有效的解决方案。非常感谢Martin R向我展示了他上面链接的帖子(解析惯用法swift(3)数据流

Alright, so I have a working solution. Big thanks to Martin R for showing me the post he linked above (Idiomatic method of parsing swift(3) data streams)

我基本上从Martin R链接的类中取出并修改它以使用NSData对象而不是Data对象:
class DataStream {
let data:NSData
var index = 0
var atEnd:Bool {
return index> = self.data.length
}

I basically took the class from the post Martin R linked and modified it to use an NSData object instead of a Data object: class DataStream { let data : NSData var index = 0 var atEnd : Bool { return index >= self.data.length }

init(data:NSData) {
    self.data = data
}

func next() -> UInt8? {
    guard !self.atEnd else { return nil }
    let byte = self.data.subdata(with: NSRange(location: self.index, length: 1))[0]
    self.index += 1
    return byte
}

func next(_ count:Int) -> NSData? {
    guard self.index + count <= self.data.length else { return nil }
    let subdata = self.data.subdata(with: NSRange(location: self.index, length: count))
    self.index += count
    return subdata as NSData?
}

func upTo(_ marker:UInt8) -> NSData? {
    if let end = (self.index..<self.data.length).index( where: { self.data.base64EncodedData()[$0] == marker } ) {
        let upTo = self.next(end - self.index)
        self.skip() // consume the marker
        return upTo
    }
    else {
        return nil
    }
}

func skip(_ count:Int = 1) {
    self.index += count
}

func skipThrough(_ marker:UInt8) {
    if let end = (self.index..<self.data.length).index( where: { self.data.base64EncodedData()[$0] == marker } ) {
        self.index = end + 1
    }
    else {
        self.index = self.data.length
    }
}

}

使用此DataStream类以及一对NSData方法,我能够模仿java方法的行为DataInputStream.ReadInt():

Using this DataStream class along with a couple NSData methods, I was able to mimic the behavior of the java method DataInputStream.ReadInt():

var someID : Int = 0
        //get the part of the data that represents someID
        guard let someIDData = dataStream.next(4 /*size of someID in the data*/) else { fatalError("Error getting someID bytes")}
        //convert the data bytes to an Int
        someIDData.getBytes(&someID, length: someIDData.length)

如果有人有更好的方法可以完成这个,我很乐意听到!我是Swift的新手,所以这可能不是最好的方式。这适用于Swift 3.1。

If someone has a better way to accomplish this, I would love to hear! I am new to Swift so this may not be the best way. This works with Swift 3.1.

这篇关于Swift将字节数组转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆