Skip to content

Instantly share code, notes, and snippets.

@bhaskarvk
Last active August 29, 2015 14:16
Show Gist options
  • Save bhaskarvk/eb4587f27157129d9c78 to your computer and use it in GitHub Desktop.
Save bhaskarvk/eb4587f27157129d9c78 to your computer and use it in GitHub Desktop.
Vectorized functions to convert ipv4 to/from integer
# Vectorized functions to convert ipv4 to/from integer
require(bitops) # required for unsigned int bitwise ops
int_to_ipv4 <- function(i) {
return(lapply(i,function(x) {
paste(bitAnd(bitShiftR(x,c(24,16,8,0)),0xFF),collapse='.')
}))
}
ipv4_to_int <- function(i) {
return(lapply(i,function(x) {
sum(bitShiftL(as.integer(strsplit(x,'.',fixed = T)[[1]]),c(24,16,8,0)))
}))
}
# Parallel versions
require(parallel)
par_int_to_ipv4 <- function(i) {
return(mclapply(i,function(x) {
paste(bitAnd(bitShiftR(x,c(24,16,8,0)),0xFF),collapse='.')
}))
}
par_ipv4_to_int <- function(i) {
return(mclapply(i,function(x) {
sum(bitShiftL(as.integer(strsplit(x,'.',fixed = T)[[1]]),c(24,16,8,0)))
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment