R Vij - 3 months ago 7
R Question

# Converting non-integer decimal numbers to binary

data frame input (DF)

``````a
123.213
4343.344
3434.43255
422.45
34534
``````

results required in binary (16 bits)

I have tried a function

``````intTobits
rawTobits
``````

but didn't worked for me

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)
sub("0+\$|[.]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"
``````