Skip to content

Instantly share code, notes, and snippets.

@greim
Created February 9, 2015 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greim/2dcedcf3c42ad6b5258f to your computer and use it in GitHub Desktop.
Save greim/2dcedcf3c42ad6b5258f to your computer and use it in GitHub Desktop.
Binary walk function
/*
* Home in on a number in binary search fashion.
* binWalk(2048) === 1024
* binWalk(2048, -1) === 512
* binWalk(2048, -1, -1) === 256
* binWalk(2048, -1, -1, -1) === 128
* binWalk(2048, -1, 1) === 1536
*/
function binWalk(n){
var lo = 0, hi = n, pointer = Math.floor(n/2)
for (var i = 1; i<arguments.length; i++){
var arg = arguments[i]
if (arg > 0) {
lo = pointer
} else {
hi = pointer
}
pointer = lo + Math.floor((hi - lo) / 2)
}
return pointer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment