От десятичной до нормализованной двойной точности:
library(BMS)
from10toNdp <- function(my10baseNumber) {
out <- list()
# Handle special cases (0, Inf, -Inf)
if (my10baseNumber %in% c(0,Inf,-Inf)) {
if (my10baseNumber==0) { out <- "0000000000000000000000000000000000000000000000000000000000000000" }
if (my10baseNumber==Inf) { out <- "0111111111110000000000000000000000000000000000000000000000000000" }
if (my10baseNumber==-Inf) { out <- "1111111111110000000000000000000000000000000000000000000000000000" }
} else {
signBit <- 0 # assign initial value
from10to2 <- function(deciNumber) {
binaryVector <- rep(0, 1 + floor(log(deciNumber, 2)))
while (deciNumber >= 2) {
theExpo <- floor(log(deciNumber, 2))
binaryVector[1 + theExpo] <- 1
deciNumber <- deciNumber - 2^theExpo }
binaryVector[1] <- deciNumber %% 2
paste(rev(binaryVector), collapse = "")}
#Sign bit
if (my10baseNumber<0) { signBit <- 1
} else { signBit <- 0 }
# Biased Exponent
BiasedExponent <- strsplit(from10to2(as.numeric(substr(sprintf("%a", my10baseNumber), which(strsplit( sprintf("%a", my10baseNumber), "")[[1]]=="p")+1, length( strsplit( sprintf("%a", my10baseNumber), "")[[1]]))) + 1023), "")[[1]]
BiasedExponent <- paste(BiasedExponent, collapse='')
if (nchar(BiasedExponent)<11) {BiasedExponent <- paste(c( rep(0,11-nchar(BiasedExponent)), BiasedExponent),collapse='') }
# Significand
significand <- BMS::hex2bin(substr( sprintf("%a", my10baseNumber) , which(strsplit( sprintf("%a", my10baseNumber), "")[[1]]=="x")+3, which(strsplit( sprintf("%a", my10baseNumber), "")[[1]]=="p")-1))
significand <- paste(significand, collapse='')
if (nchar(significand)<52) {significand <- paste(c( significand,rep(0,52-nchar(significand))),collapse='') }
out <- paste(c(signBit, BiasedExponent, significand), collapse='')
}
out
}
Следовательно,
from10toNdp(0.1)
# "0011111110111001100110011001100110011001100110011001100110011010"