如何在Swift中以littleEndian方式反转NSData输出?

时间:2015-05-12 15:25:10

标签: swift nsdata endianness

嘿伙计们我从NSData得到这个输出:< 00000100 84000c00 071490fe 4dfbd7e9>

那么我怎样才能在Swift中对其进行字节反转并输出:< 00000001 0084000c 1407fe90 fb4de9d7>?

3 个答案:

答案 0 :(得分:10)

这应该可以交换数据中的每对相邻字节。 我们的想法是将字节解释为UInt16整数数组 并使用内置的byteSwapped属性。

func swapUInt16Data(data : NSData) -> NSData {

    // Copy data into UInt16 array:
    let count = data.length / sizeof(UInt16)
    var array = [UInt16](count: count, repeatedValue: 0)
    data.getBytes(&array, length: count * sizeof(UInt16))

    // Swap each integer:
    for i in 0 ..< count {
        array[i] = array[i].byteSwapped // *** (see below)
    }

    // Create NSData from array:
    return NSData(bytes: &array, length: count * sizeof(UInt16))
}

如果您的实际意图是从(外部)转换数据 对于主机(本机)字节顺序的big-endian表示(在所有当前的iOS和OS X设备上恰好是little-endian)然后你应该用

替换***
array[i] = UInt16(bigEndian: array[i])

示例:

var bytes : [UInt8] = [1, 2, 3, 4, 5, 6, 7, 8]
let data = NSData(bytes: &bytes, length: bytes.count)
print(data)
// <01020304 05060708>
print(swapUInt16Data(data))
// <02010403 06050807>

Swift 3更新:通用withUnsafeMutableBytes() 方法允许获得字节的UnsafeMutablePointer<UInt16> 并直接修改它们:

func swapUInt16Data(data : Data) -> Data {
    var mdata = data // make a mutable copy
    let count = data.count / MemoryLayout<UInt16>.size
    mdata.withUnsafeMutableBytes { (i16ptr: UnsafeMutablePointer<UInt16>) in
        for i in 0..<count {
            i16ptr[i] =  i16ptr[i].byteSwapped
        }
    }
    return mdata
}

示例:

let data = Data(bytes: [1, 2, 3, 4, 5, 6, 7, 8])
print(data as NSData) // <01020304 05060708>

let swapped = swapUInt16Data(data: data)
print(swapped as NSData) // <02010403 06050807>

答案 1 :(得分:3)

CoreFoundation有CFSwapInt32BigToHostCFSwapInt32LittleToHost以及其他交换功能。

在swift3中它看起来像这样

struct FileHeader {
    var magicNumber: UInt32 = 0
    var count: UInt32 = 0
    var width: UInt32 = 0
    var height: UInt32 = 0

    static func create(data: Data) -> FileHeader {
        let structSize = MemoryLayout<FileHeader>.size
        assert(data.count >= structSize)
        var result = FileHeader()
        let nsdata = data as NSData
        nsdata.getBytes(&result, range: NSRange(location: 0, length: structSize))
        result.magicNumber = CFSwapInt32BigToHost(result.magicNumber)
        result.count = CFSwapInt32BigToHost(result.count)
        result.width = CFSwapInt32BigToHost(result.width)
        result.height = CFSwapInt32BigToHost(result.height)
        return result
    }
}

答案 2 :(得分:0)

对于某些人可能想要限制字节模式,这将是一个解决方案:

func swap<U:IntegerType>(data:NSData,_ :U.Type) -> NSData{
    var length = data.length / sizeof(U)
    var bytes = [U](count: length, repeatedValue: 0)
    data.getBytes(&bytes, length: data.length)
    // since byteSwapped isn't declare in any protocol, so we have do it by ourselves manually.
    var inverse = bytes.enumerate().reduce([U](count: length, repeatedValue: 0)) { (var pre, ele) -> [U] in
        pre[length - 1 - ele.index] = ele.element
        return pre
    }
    return NSData(bytes: inverse, length: data.length)
}

例如:

swap(data:data,UInt8.self)
//before <0c20207b 17> 
//after <177b2020 0c>

swap(data:anotherData,UInt16.self)
//before <8e004c01 84008f05 0701>
//after <07018f05 84004c01 8e00>