[R] Binary information convert into hexadecimal

Alberto Monteiro albmont at centroin.com.br
Fri Mar 23 13:41:11 CET 2007


Corinna Schmitt wrote:
> 
> Given is binary information and should be translated into integer and
> afterwards into hexadecimal:
> 
> 0000  0  0
>
If you have a _string_ of 0s and 1s, and you want to convert
it to an integer, I think the best way should be:

(1) convert to a vector of 0s and 1s
(2) convert to integer
(3) an integer to hex conversion is trivial (sprinf("%x", n))

(1): 
  as.integer(unlist(strsplit("0100101", NULL))) 
will do the job: 
strsplit breaks the string, unlist transforms the resulting list
into a vector of (length-one) strings, and as.integer converts
the strings into integers (0 or 1).

(2): 
  x <- c(1, 1, 0, 1, 0)
  n <- sum(x * 2^seq(length(x)-1, 0, -1))

x is the vector of 0s and 1s from (1) above. 
length(x) is its length. 
seq(length(x) - 1, 0, -1) will be the vector of integers
(in this case) 4, 3, 2, 1, 0. 
2^seq(length(x)-1, 0, -1) will be the powers of two 16, 8, 4, 2, 1.
x * 2^... will form the terms of the polynomial
sum will compute 2^(n-1) x[0] + 2^(n-2) x[1] + ... + 2 * x[n-1] + x[n]

Alberto Monteiro



More information about the R-help mailing list