Skip to content

Instantly share code, notes, and snippets.

@kmuralidharan91
Created April 10, 2020 15:28
Show Gist options
  • Save kmuralidharan91/f710ebb191274eef7cf0dce3393a2d38 to your computer and use it in GitHub Desktop.
Save kmuralidharan91/f710ebb191274eef7cf0dce3393a2d38 to your computer and use it in GitHub Desktop.
public extension Array where Array.Element == UInt8 {
func getString(atIndex: Int, count: Int) -> String? {
guard let bytes = self.slice(atIndex, count: count) else { return nil }
guard let string = String(bytes: bytes, encoding: .utf8)?.trim() else { return nil }
return string
}
func getInt(atIndex: Int, count: Int) -> Int? {
guard let bytes = self.slice(atIndex, count: count) else { return nil }
let int = bytes.withAlignedBytes {$0.load(as: UInt16.self)}
return Int(int)
}
func getDouble(atIndex: Int, count: Int) -> Double? {
guard let bytes = self.slice(atIndex, count: count) else { return nil }
let double = bytes.withAlignedBytes {$0.load(as: Double.self)}
return double
}
func getDecimal(atIndex: Int, count: Int) -> Decimal? {
guard let bytes = self.slice(atIndex, count: count) else { return nil }
let decimal = bytes.withAlignedBytes {$0.load(as: Decimal.self)}
return decimal
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment