将非整数十进制数字转换为二进制 [英] Converting non-integer decimal numbers to binary

查看:321
本文介绍了将非整数十进制数字转换为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据帧输入(DF)

a
123.213
4343.344
3434.43255
422.45
34534

结果以二进制(16位)为必需

results required in binary (16 bits)

我尝试过一个功能

intTobits
rawTobits

但没有为我工作

推荐答案

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"         

这篇关于将非整数十进制数字转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆