Learn R Programming

sfsmisc (version 0.9-4)

digitsBase: Digit/Bit Representation of Integers in any Base

Description

Compute the vector of digits $A$ of the base $b$ representation of a number $N$, $N = \sum_{k=0}^M A_{M-k} b ^ k$.

Usage

digitsBase(x, base = 2, ndigits = 1 + floor(log(max(x), base)))

Arguments

x
non-negative integer (vector) whose base base digits are wanted.
base
integer, at least 2 specifying the base for representation.
ndigits
number of bits/digits to use.

Value

  • a matrix m where m[,i] corresponds to x[i].

    c( result ) then contains the blocks in proper order ..

Examples

Run this code
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) drop(digitsBase(n, base = base))
digits(128, base = 8) # 2 0 0

hexdig <- c(0:9, LETTERS[1:6]) #-- hexadesimal coding :
i <- c(1:20, 100:120) # e.g.
M <- digitsBase(i, 16)
cM <- hexdig[1 + M]; dim(cM) <- dim(M)
sub("^0+","", apply(cM,2,paste, collapse=""))

Run the code above in your browser using DataLab