Converting non-integer decimal numbers to binary

偶尔善良 提交于 2019-12-11 06:25:22

问题


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


回答1:


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"         


来源:https://stackoverflow.com/questions/38841830/converting-non-integer-decimal-numbers-to-binary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!