Learn R Programming

IP (version 0.1.7)

Bitwise-methods: Bitwise operations

Description

Methods for IP bitwise operations !e1 e1 & e2 e1 | e2 e1 %>>% e2 e1 %<<% e2 e1 ^ e2 ip.xor(e1 , e2 ) ipv4.netmask(n) ipv6.netmask(n) ipv4.hostmask(n) ipv6.hostmask(n)

Arguments

Value

an object of either an 'IPv4', 'IPv6' or 'IP' class

Methods

!x

x & y

x | y

x %>>% n

x %<<% n

ipv4.netmask(n)

ipv6.netmask(n)

ipv4.hostmask(n)

ipv6.hostmask(n)

Details

Arguments:

  • e1 : an object of either an 'IPv4', 'IPv6' or 'IP' class

  • e2 : an object of either an 'IPv4', 'IPv6' or 'IP' class except for shifts where e2 is like 'n'

  • n : an integer in the range (0,32) for IPv4 or in the (0,128) for IPv6 for masking methods

The &, | and ! operators behave differently from their base R counterparts in that they perform bitwise operation much like in the C language.

  • & : bitwise AND

  • | : bitwise non exclusive OR

  • ! : bitwise NOT

ip.xor() provides a faster alternative to base xor().

%>>% and %<<% perform left (binary division) and right shift (binary multiplication) respectively.

The *.netmask() and *.hostmask() functions return the net and host mask of specified length n.

Examples

Run this code
##
private.network <- ipv4r("192.0.0.0/16")
##
(mask.len <- ceiling(log2(ip.range(private.network))))
##
ip <- ipv4("192.168.1.1") 
##
(netmask <- ipv4.netmask(mask.len))
##
ip & netmask
##
(hostmask <- ipv4.hostmask(mask.len))
##
ip & hostmask
##
((ip & netmask) | (ip & hostmask) )==ip
## 2 complement
((!ip) + 1L)==-ip
##
ipv4('0.0.0.2') %>>% 1L
##
ipv4('0.0.0.2') %<<% 1L
##
## branchless swap
##
ipv4.ifelse <- function(test, yes, no){
  ## 
  if( ( class(yes)!='IPv4' ) | ( class(no)!='IPv4' ) ){
    stop('both arguments should be of class IPv4')
  }
  ##
  ip.xor(
    no
    , ip.xor(
      no, yes
    ) & -(ipv4(test)) ## mask
  )
}
##
x <- ipv4('192.168.0.0') + 1:5
## recycling without warning (yet)
y <- x + c(1,-1)
##
test <- x < y
##
data.frame(
  x, y, test, res= ipv4.ifelse(test , x,y)
)
##
##
##
ip6 <- ipv6("2606:2800:220:1:248:1893:25c8:1946")
## Unicast addresses global routing prefix
ip6 & ipv6.netmask(48)
## Subnet ID
ip6 & (ipv6.hostmask(128-16) %<<% 64L)
## Interface ID 
ip6 & ipv6.hostmask(64)

Run the code above in your browser using DataLab