[R] Conversion to Binary (base2)

Duncan Murdoch murdoch at stats.uwo.ca
Thu Sep 25 23:28:28 CEST 2008


On 25/09/2008 4:22 PM, Jason Thibodeau wrote:
> This is almost doing what I want.
> here is a snippet of my code, which is writing the x coordinate (converted
> to binary), and the y coordinate to a file. The major problem at this point:
> the paces between each digit in the cat. What is causing this?

cat() adds a space between the things it outputs.  If you put sep="" 
you'll lose the space (or you could use collapse="" in the paste).

To reduce the number of bits to 17, just index the first 17 bits that 
intToBits gives you, or the last ones after the rev.

For example,

 > x <- 123
 > paste(rev(as.integer(intToBits(as.integer(x))[1:17])), collapse="")
[1] "00000000001111011"


> 
> code:
> sink("generated.txt", append = TRUE)
> cat(paste(rev(as.integer(intToBits(as.integer(input[xpointer,1]))))))
> 
> output:
> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0,0
> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1,0.0998004
> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0,0.1996008
> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1,0.2994012
> 
> Thanks so much for the help, you all are life savers!
> 
> On Thu, Sep 25, 2008 at 4:11 PM, Jason Thibodeau <jbloudg20 at gmail.com>wrote:
> 
>> This seems to work well. After playing with it for a while, however, I
>> can't seem to find a way to fix the number of binary digits to say, 17. Am I
>> just missing something, or am I getting lost in the type conversion?
>>
>> The help page for intToBits said parameter n, and I tried that to no avail.
>>
>>
>> On Thu, Sep 25, 2008 at 3:56 PM, Duncan Murdoch <murdoch at stats.uwo.ca>wrote:
>>
>>> On 9/25/2008 3:33 PM, Jason Thibodeau wrote:
>>>
>>>> Hello,
>>>>
>>>> Is there a simple way to take an input, and convert the decimal integers
>>>> to
>>>> binary? In this case, I have a CSV file, and I need to convert the first
>>>> column of every line to binary.
>>>>
>>> Yes, the intToBits function does what you want.  It works with raw vector
>>> output and integer vector input, so you need a few type conversions, but
>>> essentially this is simple:
>>>
>>>> x <- 123
>>>> paste(rev(as.integer(intToBits(as.integer(x)))), collapse="")
>>> [1] "00000000000000000000000001111011"
>>>
>>> Duncan Murdoch
>>>
>>>
>>
>> --
>> Jason Thibodeau
>>
> 
> 
>



More information about the R-help mailing list