来自UInt8的NSData [英] NSData from UInt8

查看:134
本文介绍了来自UInt8的NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近迅速找到了源代码,我正在尝试将其发布到Objective-C.我无法理解的一件事是:

I have recently found a source code in swift and I am trying to get it to objective-C. The one thing I was unable to understand is this:

var theData:UInt8!

theData = 3;
NSData(bytes: [theData] as [UInt8], length: 1)

有人可以帮助我获得与Obj-C相当的产品吗?

Can anybody help me with the Obj-C equivalent?

仅提供一些上下文,我需要将UInt8作为UInt8发送到CoreBluetooth外围设备(CBPeripheral).浮点数或整数将不起作用,因为数据类型太大.

Just to give you some context, I need to send UInt8 to a CoreBluetooth peripheral (CBPeripheral) as UInt8. Float or integer won't work because the data type would be too big.

推荐答案

如果您将Swift代码编写为稍微简单一些

If you write the Swift code slightly simpler as

var theData : UInt8 = 3
let data = NSData(bytes: &theData, length: 1)

然后将其转换为Objective-C相对简单:

then it is relatively straight-forward to translate that to Objective-C:

uint8_t theData = 3;
NSData *data = [NSData dataWithBytes:&theData length:1];

对于多个字节,您将使用数组

For multiple bytes you would use an array

var theData : [UInt8] = [ 3, 4, 5 ]
let data = NSData(bytes: &theData, length: theData.count)

转换为Objective-C,

which translates to Objective-C as

uint8_t theData[] = { 3, 4, 5 };
NSData *data = [NSData dataWithBytes:&theData length:sizeof(theData)];

(您可以在最后一条语句中省略address-of运算符, 参见例如数组的地址如何等于它在C中的值?).

(and you can omit the address-of operator in the last statement, see for example How come an array's address is equal to its value in C?).

这篇关于来自UInt8的NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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