Skip to content

Instantly share code, notes, and snippets.

@JanGorman
Created April 19, 2016 14:41
Show Gist options
  • Select an option

  • Save JanGorman/8f683732eadf0cc8630b3c1e09eeffbe to your computer and use it in GitHub Desktop.

Select an option

Save JanGorman/8f683732eadf0cc8630b3c1e09eeffbe to your computer and use it in GitHub Desktop.
func toInt24(value: Int) -> NSData {
var result = [UInt8]()
result.append(UInt8(value >> 16))
result.append(UInt8(value >> 8))
result.append(UInt8(value))
return NSData(bytes: result, length: result.count)
}
func int24FromData(data: NSData, inout range: NSRange) -> Int {
let offset = sizeof(UInt8)
var read = -1
data.getBytes(&read, range: range)
var result = (read & 0xff) << 16
range.location += offset
data.getBytes(&read, range: range)
result |= (read & 0xff) << 8
range.location += offset
data.getBytes(&read, range: range)
result |= read & 0xff
range.location += offset
return result
}
let data = NSMutableData(data: toInt24(100))
data.appendData(toInt24(50))
var range = NSRange(location: 0, length: sizeof(UInt8))
let first = int24FromData(data, range: &range)
let second = int24FromData(data, range: &range)
@bonkey

bonkey commented Apr 19, 2016

Copy link
Copy Markdown

Didn't think about it much, but maybe it will give you some insight to start

import Foundation

func toInt24(value: Int) -> NSData {
    var result = [UInt8]()
    result.append(UInt8(value >> 16))
    result.append(UInt8(value >> 8))
    result.append(UInt8(value))
    return NSData(bytes: result, length: result.count)
}

func int24FromData(data: NSData) -> [Int] {
    let dataLength = data.length
    let biteSize = sizeof(UInt8)
    let bitesCount = dataLength / biteSize

    var numbers = [UInt8](count: bitesCount, repeatedValue: 0)

    data.getBytes(&numbers, length: dataLength)

    return numbers.enumerate().filter({ idx, el in (idx + 1) % 3 == 0}).map { Int($1) }
}

let data = NSMutableData(data: toInt24(100))
data.appendData(toInt24(50))
data.appendData(toInt24(201))
data.appendData(toInt24(202))
data.appendData(toInt24(203))
data.appendData(toInt24(204))

print(int24FromData(data))
// return: [100, 50, 201, 202, 203, 204]

@JanGorman

Copy link
Copy Markdown
Author

It is much appreciated 🙇 The stream comes with mixed types (24 bit ones, 32 bit ones as well as strings) in it. But could extract sub ranges for expected areas and work on those in the simplified fashion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment