# Re: [R] binary numbers

From: Martin Maechler (maechler@stat.math.ethz.ch)
Date: Thu 15 Apr 2004 - 22:55:09 EST

```Message-id: <16510.34349.928143.242715@gargle.gargle.HOWL>

```

>>>>> "Samuel" == Samuel Edward Kemp <sam.kemp2@ntlworld.com>
>>>>> on Wed, 14 Apr 2004 22:20:24 +0100 writes:

Samuel> Hi, Is there a function in R that lets one represent
Samuel> an integer in binary format for a given number of
Samuel> bits? So an example would be....

>> binary.function(num=5, num.of.bits=8) "00000101"

Samuel> Or, is this something I have to write myself?

no. In package "sfsmisc", there's also

>> digitsBase package:sfsmisc R Documentation
>>
>> Digit/Bit Representation of Integers in any Base
>>
>> Description:
>>
>> Compute the vector of "digits" A of the 'base' b representation of
>> a number N, N = sum(k = 0:M ; A[M-k] * b^k).
>>
>> Usage:
>>
>> digitsBase(x, base = 2, ndigits = 1 + floor(log(max(x), base)))

e.g.,

> library(sfsmisc) # after installing it

> digitsBase(5, base= 2, 10)
[,1]
[1,] 0
[2,] 0
[3,] 0
[4,] 0
[5,] 0
[6,] 0
[7,] 0
[8,] 1
[9,] 0
[10,] 1

> empty.dimnames(digitsBase(0:33, 2)) # binary

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 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

where you see that it does work vectorized.

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help