Converts an integer (Base10) to a binary (Base2) number. It also converts a logical vector to a binary (Base2) number (see examples).

as.binary(x, signed=FALSE, littleEndian=FALSE, size=2, n=0, logic=FALSE)

Arguments

x

integer or logical vector.

signed

TRUE or FALSE. Unsigned by default. (two's complement)

littleEndian

if TRUE. Big Endian if FALSE.

size

in Byte. Needed if signed is set. (by default 2 Byte)

n

in Bit. Can be set if unsigned is set to TRUE. (by default 0 Bit = auto)

logic

If set to TRUE, x is expected as logical vector.

Value

a vector of class binary.

Details

The binary number is represented by a logical vector. The bit order usually follows the same endianess as the byte order. No floating-point support. If logic is set to TRUE an integer vector is intepreted as a logical vector (>0 becomes TRUE and 0 becomes FALSE)

  • Little Endian (LSB) ---> (MSB)

  • Big Endian (MSB) <--- (LSB)

Auto switch to signed if num < 0.

See also

Examples

as.binary(0xAF)
#> [1] 1 0 1 0 1 1 1 1
as.binary(42)
#> [1] 1 0 1 0 1 0
as.binary(42, littleEndian=TRUE)
#> [1] 0 1 0 1 0 1
as.binary(c(0xAF, 0xBF, 0xFF))
#> [[1]]
#> [1] 1 0 1 0 1 1 1 1
#> 
#> [[2]]
#> [1] 1 0 1 1 1 1 1 1
#> 
#> [[3]]
#> [1] 1 1 1 1 1 1 1 1
#> 
as.binary(c(2,4,8,16,32), signed=TRUE, size=1)
#> [[1]]
#> [1] 0 0 0 0 0 0 1 0
#> 
#> [[2]]
#> [1] 0 0 0 0 0 1 0 0
#> 
#> [[3]]
#> [1] 0 0 0 0 1 0 0 0
#> 
#> [[4]]
#> [1] 0 0 0 1 0 0 0 0
#> 
#> [[5]]
#> [1] 0 0 1 0 0 0 0 0
#> 
as.binary(-1, signed=TRUE, size=1)
#> [1] 1 1 1 1 1 1 1 1
as.binary(1:7, n=3)
#> [[1]]
#> [1] 0 0 1
#> 
#> [[2]]
#> [1] 0 1 0
#> 
#> [[3]]
#> [1] 0 1 1
#> 
#> [[4]]
#> [1] 1 0 0
#> 
#> [[5]]
#> [1] 1 0 1
#> 
#> [[6]]
#> [1] 1 1 0
#> 
#> [[7]]
#> [1] 1 1 1
#> 
as.binary(sample(2^8,3),n=8)
#> [[1]]
#> [1] 0 1 0 0 0 0 0 0
#> 
#> [[2]]
#> [1] 1 1 0 0 1 0 0 1
#> 
#> [[3]]
#> [1] 1 0 0 1 1 0 1 0
#> 
as.binary(c(1,1,0), signed=TRUE, logic=TRUE)
#> [1] 0 0 0 0 0 1 1 0
as.binary(c(TRUE,TRUE,FALSE), logic=TRUE)
#> [1] 1 1 0