1

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

2
  • in that case only integers were used but here we have numeric values in decimal fractions also Commented Aug 9, 2016 at 4:08
  • 3
    I don't think there is any preexisting function. You have to write your own. Commented Aug 9, 2016 at 4:14

1 Answer 1

3

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"         
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.