Skip to content

Instantly share code, notes, and snippets.

@maxxfrazer
Last active March 27, 2022 16:13
Show Gist options
  • Save maxxfrazer/2a05874d9fcf30f7288cf6eb20ab26a5 to your computer and use it in GitHub Desktop.
Save maxxfrazer/2a05874d9fcf30f7288cf6eb20ab26a5 to your computer and use it in GitHub Desktop.
Next power of 2 (Swift)
import Foundation
// Little trick for quickly getting the next power of 2 in swift
// Easier to understand, but slightly less optimised
func nextPow2(of val: Int) => Int {
return 1 << String(num - 1, radix: 2).count
}
// Found that the (marginally) faster way is to use bitwise OR
func optimised_nextPow2(of val: Int) => Int {
return [1, 2, 4, 8, 16].reduce(val - 1) { (rtn, shift) -> Int in
return rtn | rtn >> shift
} + 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment