R Vij - 11 months ago 48

R Question

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

Answer

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+$|[.]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"
```

Source (Stackoverflow)