[R] Convert bits to numbers in base 10

Michael Conklin michael.conklin at markettools.com
Thu Apr 9 23:59:56 CEST 2009


Alternatively

(nn <- c(1, 0, 0, 1, 0, 1,0))
 [1] 1 0 0 1 0 1 0

  sum(2^(0:(length(nn)-1))*nn)

but of course it depends if your bits are stored big-endian or little-endian
so you might want


  sum(2^((length(nn)-1):0)*nn)


I like Marc's approach better (certainly more elegant). If you have the big vs little endian issue you can just remove the rev from Marc's code below.

Michael Conklin


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Marc Schwartz
Sent: Thursday, April 09, 2009 4:51 PM
To: Jorge Ivan Velez
Cc: R-help; Gang Chen
Subject: Re: [R] Convert bits to numbers in base 10

I suspect that Gang was looking for something along the lines of:

 > sum(2 ^ (which(as.logical(rev(nn))) - 1))
[1] 74

You might also want to look at the digitsBase() function in Martin's
sfsmisc package on CRAN.

HTH,

Marc Schwartz

On Apr 9, 2009, at 4:34 PM, Jorge Ivan Velez wrote:

> Dear Gang,
> Try this:
>
> nn <- c(1, 0, 0, 1, 0, 1,0)
> paste(nn,sep="",collapse="")
>
> See ?paste for more information.
>
> HTH,
>
> Jorge
>
>
> On Thu, Apr 9, 2009 at 5:23 PM, Gang Chen <gangchen6 at gmail.com> wrote:
>
>> I have some bits stored like the following variable nn
>>
>> (nn <- c(1, 0, 0, 1, 0, 1,0))
>> [1] 1 0 0 1 0 1 0
>>
>> not in the format of
>>
>> 1001010
>>
>> and I need to convert them to numbers in base 10. What's an easy
>> way to do
>> it?
>>
>> TIA,
>> Gang

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list