Skip to content

Instantly share code, notes, and snippets.

@yoavram
Created November 1, 2012 13:53
Show Gist options
  • Save yoavram/3993746 to your computer and use it in GitHub Desktop.
Save yoavram/3993746 to your computer and use it in GitHub Desktop.
a function that transforms a vector of bits ( c(0,1,1,0,0) ) to an unsigned integer (6). Includes a test as an example at the bottom.
bits.to.uint <- function(bits) {
s=0
for (i in 1:length(bits)) {
s = s + 2^(i-1) * bits[i]
}
return(s)
}
cat(bits.to.uint( c(0,1,1,0,0) ) == 6)
cat(bits.to.uint( c(0,1,0,0,1) ) == 18 )
cat(bits.to.uint( c(1,0,0,0,0,0,0,0,1) ) == 257 )
@hadley
Copy link

hadley commented Nov 1, 2012

Vectorisation is your friend:

bits.to.uint <- function(bits) {
  sum(2 ^ (seq_along(bits) - 1) * bits)
}

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