[R] bitwise addition
Marc Schwartz (via MN)
mschwartz at mn.rr.com
Fri May 12 21:05:57 CEST 2006
On Fri, 2006-05-12 at 11:41 -0500, Nameeta Lobo wrote:
>
> Hello all again,
>
> I want to do bitwise addition in R. I am trying to generate a matrix
> 0000
> 0001
> 0010
> ....
> ....
> 1111
>
> I know the other ways of generating this matrix but I need to look at bitwise
> addition.
>
> Any suggestions???
>
> thanks a lot
>
> Nameeta
Nameeta,
I may be misunderstanding what you are trying to do, so here are two
approaches that might be helpful:
1. Presuming that each of the above rows is a binary representation of a
number x >= 0 (so we don't have to worry about two's complements) and
that you want to add the rows to get a total, you can do:
> mat
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 0 0 1
[3,] 0 0 1 0
[4,] 1 1 1 1
# This will convert each row to it's base 10 value
> apply(mat, 1, function(x) sum(x * (2 ^ ((length(x) - 1):0))))
[1] 0 1 2 15
# So just sum them
> sum(apply(mat, 1, function(x) sum(x * (2 ^ ((length(x) - 1):0)))))
[1] 18
2. If you want to actually generate the above matrix as a sequence of
binary values from a sequence of base 10 integer values, you can use the
digitsBase() function in Martin's sfsmisc package on CRAN:
install.packages("sfsmisc")
library(sfsmisc)
> t(digitsBase(1:15))
Class 'basedInt'(base = 2) [1:4]
[,1] [,2] [,3] [,4]
[1,] 0 0 0 1
[2,] 0 0 1 0
[3,] 0 0 1 1
[4,] 0 1 0 0
[5,] 0 1 0 1
[6,] 0 1 1 0
[7,] 0 1 1 1
[8,] 1 0 0 0
[9,] 1 0 0 1
[10,] 1 0 1 0
[11,] 1 0 1 1
[12,] 1 1 0 0
[13,] 1 1 0 1
[14,] 1 1 1 0
[15,] 1 1 1 1
You might also want to look at the as.intBase() function in the same
package.
HTH,
Marc Schwartz
More information about the R-help
mailing list