Skip to content

Instantly share code, notes, and snippets.

@tanner0101
Last active December 22, 2016 05:13
Show Gist options
  • Select an option

  • Save tanner0101/e720877bf7700138eb99 to your computer and use it in GitHub Desktop.

Select an option

Save tanner0101/e720877bf7700138eb99 to your computer and use it in GitHub Desktop.
Convert an arbitrary length byte array into a Swift Int
/**
IntExtensions.swift
Convert an arbitrary length byte array into a Swift Int
<https://gist.github.com/tannernelson/e720877bf7700138eb99>
*/
extension Int {
static func fromByteArray(bytes: [UInt8]) -> Int {
var int = 0
for (offset, byte) in enumerate(bytes) {
let factor: Double = Double(bytes.count) - (Double(offset) + 1);
let size: Double = 256
int += Int(byte) * Int(pow(size, factor))
}
return int
}
}
@jweinst1

jweinst1 commented Nov 3, 2016

Copy link
Copy Markdown

In swift 3, you need bytes.enumerated()

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