digitsBase              package:sfsmisc              R Documentation

_D_i_g_i_t/_B_i_t _R_e_p_r_e_s_e_n_t_a_t_i_o_n _o_f _I_n_t_e_g_e_r_s _i_n _a_n_y _B_a_s_e

_D_e_s_c_r_i_p_t_i_o_n:

     Integer number representations in other Bases.

     Formally, for every element N ='x[i]', compute the (vector of)
     "digits" A of the 'base' b representation of the number N, N =
     sum(k = 0:M ; A[M-k] * b^k).
      Revert such a representation to integers.

_U_s_a_g_e:

     digitsBase(x, base = 2, ndigits = 1 + floor(log(max(x), base)))
     ## S3 method for class 'basedInt':
     as.integer(x, ...)
     ## S3 method for class 'basedInt':
     print(x, ...)

     as.intBase(x, base = 2)

_A_r_g_u_m_e_n_t_s:

       x: For 'digitsBase()': non-negative integer (vector) whose base
          'base' digits are wanted.

          For 'as.intBase()': 
           a list of numeric vectors, a character vector, or an integer
          matrix as returned by 'digitsBase()', representing digits in
          base 'base'. 

    base: integer, at least 2 specifying the base for representation.

 ndigits: number of bits/digits to use.

     ...: potential further arguments passed to methods, notably
          'print'.

_V_a_l_u_e:

     For 'digitsBase()', an object, say 'm', of class '"basedInt"'
     which is basically a ('ndigits' x 'n') 'matrix' where 'm[,i]'
     corresponds to 'x[i]', 'n <- length(x)' and 'attr(m,"base")' is
     the input 'base'.

     'as.intBase()' and the 'as.integer' method for 'basedInt' objects
     return an 'integer' vector.

_N_o_t_e:

     'digits' and 'digits.v' are now deprecated and will be removed
     from the 'sfsmisc' package.

_A_u_t_h_o_r(_s):

     Martin Maechler, Dec 4, 1991 (for S-plus; then called 'digits.v').

_E_x_a_m_p_l_e_s:

     digitsBase(0:12, 8) #-- octal representation
     empty.dimnames(digitsBase(0:33, 2)) # binary

     ## This may be handy for just one number (and default decimal):
     digits <- function(n, base = 10) as.vector(digitsBase(n, base = base))
     digits(128, base = 8) # 2 0 0

     ## one way of pretty printing (base <= 10!)
     b2ch <- function(db)
             noquote(gsub("^0+(.{1,})$"," \1", apply(db, 2, paste, collapse = "")))
     b2ch(digitsBase(0:33, 2))  #->  0 1 10 11 100 101 ... 100001
     b2ch(digitsBase(0:33, 4))  #->  0 1 2 3 10 11 12 13 20 ... 200 201

     ## Hexadecimal:
     i <- c(1:20, 100:106)
     M <- digitsBase(i, 16)
     hexdig <- c(0:9, LETTERS[1:6])
     cM <- hexdig[1 + M]; dim(cM) <- dim(M)
     b2ch(cM) #->  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F 10 11 ... 6A

     ## Inverse of digitsBase() : as.integer method for the "basedInt" class
     as.integer(M)
     ## or also as.intBase() working from strings:
     (cb <- apply(digitsBase(0:33, 4), 2, paste, collapse = ""))
     ##-> "000" "001" ..... "200" "201"
     all(0:33 == as.intBase(cb, base = 4))

