NSData from UInt8
If you write the Swift code slightly simpler as
var theData : UInt8 = 3
let data = NSData(bytes: &theData, length: 1)
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)
which translates to Objective-C as
uint8_t theData[] = { 3, 4, 5 };
NSData *data = [NSData dataWithBytes:&theData length:sizeof(theData)];
(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?).
How to convert NSData to Array of UInt8 ins iOS Objective C?
To produce a stack based array try something like (code typed directly into answer, expect errors):
NSData *data = ...
UInt8 buf[data.length]; // local stack array
[data getBytes:buf length:data.length];
If you want a heap array you will need to use malloc
to allocate the memory, if you don't actually need the array just a C pointer you can use the NSData
bytes
method.
Swift 3.0 convert Data to Array UInt8
Got it!
var recived = [UInt8]()
func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
recived.removeAll()
print("recieved:\(data))")
recived.append(contentsOf: data)
}
Is there a way to cast Data to [UInt8] (a byte array) without copying, or is Unsafe the way to go?
There is no need to cast Data because it supports the subscript operator to access the UInt8
at a given index.
Incidentally it also supports isEmpty
, so you do not need to check if count is 0.
var data = Data(repeating: 0, count: 5)
data.indices.forEach { data[$0] = UInt8($0) }
print(data[2])
Data vs [UInt8]
[UInt8]
is essentially a byte array, a byte (as I'm sure you know), is comprised of 8 bits. Whilst NSData isn't simply a byte array, deep down it's underlying structure is based off one. You can easily convert between them using methods such as data.bytes
, for example.
In terms of designing APIs, I would personally recommend you design them with NSData simply because of all the extra functionality it offers over a simple byte array. Apple has already done a lot of the legwork for you, so why do it again yourself?
How can I convert my UInt8 array to Data? (Swift)
It looks like you're really trying to avoid a copy of the bytes, if not, then just init a new Data with your bytes
array:
let data2 = Data(bytes)
print("data2: \(data2)")
If you really want to avoid the copy, what about something like this?
let data1 = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: bytes.count, deallocator: .none)
print("data1: \(data1)")
What is the best way to modify a [UInt8] byte array in swift 4?
In Swift 3+ Data
can be used as a collection type containing UInt8
objects.
Having a Data
object from a String
let hello = Data("hello".utf8)
you can convert it to [UInt8]
simply with
let hello1 = [UInt8](hello)
and back to Data
let hello2 = Data(hello1)
Data
provides all manipulation API like append
, insert
, remove
Actually you don't need [UInt8]
. Given two strings as Data
objects
var hello = Data("Hello !".utf8)
let world = Data("world".utf8)
You can insert world
in hello
hello.insert(contentsOf: world, at: 6)
print(String(data: hello, encoding: .utf8)!) // "Hello world!"
And then get a range of data
let rangeOfWorld = Data(hello[6...11])
print(String(data: rangeOfWorld, encoding: .utf8)!) // "world!"
Related Topics
Swap Rootviewcontroller With Animation
How to Convert Hex Number to Bin in Swift
Swift 2 iOS 9 Do Catch Try Crashing with Unexpected Nil Found
How to Create a Fixed-Size Array of Objects
Building Pure Swift Cocoa Touch Framework
Is There a Prefix Header (Or Something with This Functionality) in Swift
How to Get the File Creation Date Using Url Resourcevalues Method in Swift 3
How May I Test the Equivalency of Enumeration Cases with Associated Values in Swift 4
What Are "Intervals" in Swift Ranges
Generating Random Numbers With Swift
How to Get User Home Directory Path (Users/"User Name") Without Knowing the Username in Swift3
How to Make Class Methods/Properties in Swift
Swift: Property Conforming to a Specific Class and in the Same Time to Multiple Protocols