如何以littleEndian方式在Swift中字节反转NSData输出? [英] How to byte reverse NSData output in Swift the littleEndian way?

查看:270
本文介绍了如何以littleEndian方式在Swift中字节反转NSData输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从NSData获得以下输出:< 00000100 84000c00 071490fe 4dfbd7e9>

I have this output from NSData: <00000100 84000c00 071490fe 4dfbd7e9>

所以我如何在Swift中对它进行字节反转并得到以下输出:< 00000001 0084000c 1407fe90 fb4de9d7>

So how could I byte reverse it in Swift and have this output: <00000001 0084000c 1407fe90 fb4de9d7>?

推荐答案

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

This should work to swap each pair of adjacent bytes in the data. The idea is to interpret the bytes as an array of UInt16 integers and use the built-in byteSwapped property.

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

如果您的实际意图是将(外部)
大尾数表示形式的数据转换为主机(本机)字节顺序(在所有当前的iOS和OS X设备上恰好是小尾数形式),则您应该将 *** 替换为

If your actual intention is to convert data from an (external) big-endian representation to the host (native) byte order (which happens to be little-endian on all current iOS and OS X devices) then you should replace *** by

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> 到字节
并直接对其进行修改:


Update for Swift 3: The generic withUnsafeMutableBytes() methods allows to obtain a UnsafeMutablePointer<UInt16> to the bytes and modify them directly:

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>

这篇关于如何以littleEndian方式在Swift中字节反转NSData输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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