Converting decimal to binary in R?
Note that intToBits()
returns a 'raw' vector, not a character vector (strings). Note that my answer is a slight extension of @nico's original answer that removes the leading "0" from each bit:
paste(sapply(strsplit(paste(rev(intToBits(12))),""),`[[`,2),collapse="")
[1] "00000000000000000000000000001100"
To break down the steps, for clarity:
# bit pattern for the 32-bit integer '12'
x <- intToBits(12)
# reverse so smallest bit is first (little endian)
x <- rev(x)
# convert to character
x <- as.character(x)
# Extract only the second element (remove leading "0" from each bit)
x <- sapply(strsplit(x, "", fixed = TRUE), `[`, 2)
# Concatenate all bits into one string
x <- paste(x, collapse = "")
x
# [1] "00000000000000000000000000001100"
Or, as @nico showed, we can use as.integer()
as a more concise way to remove the leading zero from each bit.
x <- rev(intToBits(12))
x <- paste(as.integer(x), collapse = "")
# [1] "00000000000000000000000000001100"
Just for copy-paste convenience, here's a function version of the above:
dec2bin <- function(x) paste(as.integer(rev(intToBits(x))), collapse = "")
How to convert integer number into binary vector?
There's the intToBits
function that converts any integer to a vector of 32 raws, so you can do this:
decimals <- c(3,5,11,4)
m <- sapply(decimals,function(x){ as.integer(intToBits(x))})
m
> m
[,1] [,2] [,3] [,4]
[1,] 1 1 1 0
[2,] 1 0 1 0
[3,] 0 1 0 1
[4,] 0 0 1 0
[5,] 0 0 0 0
[6,] 0 0 0 0
[7,] 0 0 0 0
[8,] 0 0 0 0
[9,] 0 0 0 0
[10,] 0 0 0 0
[11,] 0 0 0 0
[12,] 0 0 0 0
[13,] 0 0 0 0
[14,] 0 0 0 0
[15,] 0 0 0 0
[16,] 0 0 0 0
[17,] 0 0 0 0
[18,] 0 0 0 0
[19,] 0 0 0 0
[20,] 0 0 0 0
[21,] 0 0 0 0
[22,] 0 0 0 0
[23,] 0 0 0 0
[24,] 0 0 0 0
[25,] 0 0 0 0
[26,] 0 0 0 0
[27,] 0 0 0 0
[28,] 0 0 0 0
[29,] 0 0 0 0
[30,] 0 0 0 0
[31,] 0 0 0 0
[32,] 0 0 0 0
Convert binary string to binary or decimal value
You could use the packBits
function (in the base
package). Bear in mind that this function requires very specific input.
(yy <- intToBits(5))
# [1] 01 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
# [26] 00 00 00 00 00 00 00
# Note that there are 32 bits and the order is reversed from your example
class(yy)
[1] "raw"
packBits(yy, "integer")
# [1] 5
There is also the strtoi
function (also in the base
package):
strtoi("00000001001100110000010110110111", base = 2)
# [1] 20121015
strtoi("000101", base = 2)
# [1] 5
Converting non-integer decimal numbers to binary
The conversion of integer decimal numbers into binary numbers is thoroughly discussed in this post. Non-integer numbers are a different issue.
For the binary representation of floating point decimal numbers you can try this function:
floatToBin <- function(x){
int_part <- floor(x)
dec_part <- x - int_part
int_bin <- R.utils::intToBin(int_part)
dec_bin <- stringr::str_pad(R.utils::intToBin(dec_part * 2^31), 31, pad="0")
sub("[.]?0+$", "", paste0(int_bin, ".", dec_bin))
}
Note that this function only works for non-negative numbers.
This is the output for the numbers indicated in the question:
nums <- c(123.213, 4343.344, 3434.43255, 422.45, 34534)
sapply(nums, floatToBin)
#[1] "1111011.0011011010000111001010110000001"
#[2] "1000011110111.010110000001000001100010010011"
#[3] "110101101010.0110111010111011100110001100011"
#[4] "110100110.0111001100110011001100110011001"
#[5] "1000011011100110"
Convert binary vector to decimal
You could try this function
bitsToInt<-function(x) {
packBits(rev(c(rep(FALSE, 32-length(x)%%32), as.logical(x))), "integer")
}
a <- c(0,0,0,1,0,1)
bitsToInt(a)
# [1] 5
here we skip the character conversion. This only uses base
functions.
It is likely that
unbinary(paste(a, collapse=""))
would have worked should you still want to use that function.
In R decoding binary to decimal
This function doesn't convert binary to decimal, it converts Grey Encoded binary to decimal.
Note that the decode() function assumes that the input binary string is expressed using Gray encoding, which ensures that consecutive values have the same Hamming distance (Hamming, 1950).
If we look at the code, the vector is split, then run through gray2binary()
, then binary2decimal()
. I haven't heard of it before, but it's aparantly a different version of binary encoding where increasing the number by 1 only involves changing a single number. Well, what is Grey encoding? From the ?gray2binary help:
Gray encoding allows to obtain binary strings not affected by the well-known Hamming cliff problem. With Gray encoding the number of bit differences between any two consecutive values is one, whereas in binary strings this is not always true.
# Consider a five-bit encoding of values 15 and 16 using the standard
# binary coding
decimal2binary(15, 5)
[1] 0 1 1 1 1
decimal2binary(16, 5)
[1] 1 0 0 0 0
# Moving from 15 to 16 (or vice versa) all five bits need to be changed,
# but using Gray encoding the two binary strings differ by one bit.
binary2gray(decimal2binary(15, 5))
[1] 0 1 0 0 0
binary2gray(decimal2binary(16, 5))
[1] 1 1 0 0 0
We can use a simple loop to see how 1:10 looks in binary vs grey encoding
# Grey encoding
sapply(1:10, function(x) paste(binary2gray(decimal2binary(x)), collapse = ''))
[1] "1" "11" "10" "110" "111" "101" "100" "1100" "1101" "1111"
# Binary
sapply(1:10, function(x) paste(decimal2binary(x), collapse = ''))
[1] "1" "10" "11" "100" "101" "110" "111" "1000" "1001" "1010"
Related Topics
Calculating Cumulative Sum For Each Row
How to Export Multiple Data.Frame to Multiple Excel Worksheets
Simpler Population Pyramid in Ggplot2
Split Violin Plot With Ggplot2
How R Formats Posixct With Fractional Seconds
Subset Dataframe by Multiple Logical Conditions of Rows to Remove
How to Put Labels Over Geom_Bar in R With Ggplot2
How to Remove All Whitespace from a String
Incomplete Final Line' Warning When Trying to Read a .Csv File into R
How to Use Grep()/Gsub() to Find Exact Match
Why Do R Objects Not Print in a Function or a "For" Loop
Using the Rjava Package on Win7 64 Bit With R
How to Match Fuzzy Match Strings from Two Datasets
Plotting Contours on an Irregular Grid
Explain a Lazy Evaluation Quirk
Using Regex in R to Find Strings as Whole Words (But Not Strings as Part of Words)