R/bits.R

#' Bitwise function
#' @description internal functions specific to shifting bits, mostly for the bigz data type.
#' @references Some reference for the ed25519 algorithm: http://ed25519.cr.yp.to/
#' @note These functions were adapted from this gist by Johan Stén: https://gist.github.com/johansten/3859fb4f9a24a5b6fee5bef86a3ad91c

.bit <- function(h, i) {
  ind = floor(i / 8) + 1
  return(bitwAnd(bitwShiftR(as.integer(h[ind]), i %% 8), 1))
}

.bitShiftR <- function(a, n) {
  if (n < 1)
    return(a)
  if (a %% 2 == 0)
    return(as.bigz(a / 2 ^ n))
  return(as.bigz(((a - 1) / 2 ^ n)))
}

.bitAnd <- function(a1, a2) {
  a1 = as.numeric(charToRaw(as.character(a1, b = 2))) - 48
  b1 = as.numeric(charToRaw(as.character(a2, b = 2))) - 48

  mx = max(length(a1), length(b1))
  a1 = c(rep(0, mx - length(a1)), a1)
  b1 = c(rep(0, mx - length(b1)), b1)

  return(as.bigz(paste0("0b", rawToChar(as.raw(
    1 * (a1 & b1) + 48
  )))))
}

.bitOr <- function(a1, a2) {
  a1 = as.numeric(charToRaw(as.character(a1, b = 2))) - 48
  b1 = as.numeric(charToRaw(as.character(a2, b = 2))) - 48

  mx = max(length(a1), length(b1))
  a1 = c(rep(0, mx - length(a1)), a1)
  b1 = c(rep(0, mx - length(b1)), b1)

  return(as.bigz(paste0("0b", rawToChar(as.raw(
    1 * (a1 | b1) + 48
  )))))
}
froocpu/stellaR documentation built on May 17, 2019, 7:05 p.m.