Re: [R] bitwise addition

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Sat 13 May 2006 - 05:05:57 EST

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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sat May 13 05:10:30 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sat 13 May 2006 - 06:10:07 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.