Last active
October 11, 2023 13:07
-
-
Save telliott99/99ea1f4bd3f10a84ee82 to your computer and use it in GitHub Desktop.
convert NSData -> [UInt8]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let n = 256 | |
let a = Array(0..<n).map { UInt8($0) } | |
let data = NSData(bytes: a, length: a.count) | |
print(data) // "<0001...feff>" | |
let stream = NSInputStream(data: data) | |
stream.open() | |
//------------------------------------ | |
// now, allocate the memory we need | |
var buffer = Array<UInt8>(count: n, repeatedValue: 0) | |
// and read the bytes into the buffer | |
let r = stream.read(&buffer, maxLength: n) | |
// result indicates the number of bytes read | |
print(r) // 256 | |
print(stream.hasBytesAvailable) // false | |
//------------------------------------ | |
let R = Array(0..<n) | |
let arr: [UInt8] = R.map { buffer[$0] } | |
print(arr) // [0, 1, 2 ... 253, 254, 255] | |
//------------------------------------ | |
// forgot I had this more direct approach!! | |
var b: [UInt8] = [0x60,0x61,0x62] | |
b | |
let d = NSData(bytes: b, length: 3) | |
d.length // 3 | |
let count = d.length/sizeof(UInt8) | |
var a4 = [UInt8](count: count, repeatedValue: 0) | |
d.getBytes(&a4, length:count * sizeof(UInt8)) | |
a4 // [96, 97, 98] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment