编辑:我意识到我假设输入是character,这对我来说可能是一个错误的假设。我相信相信 R 来保存你所有的 0 和 1(考虑到 R FAQ 7.31)有点信任,但我会保持原样,除非/直到出现更好的情况。
这很有趣...不确定是否有处理非十进制浮点数的 R 函数,所以这里有一个 ...
#' Convert floating-point binary to decimal
#'
#' @param s 'character'
#' @return 'numeric'
#' @examples
#' tests <- c("10100101", "0", "10100101.01", "-10100101", "-10100101.01", "111101111.010111")
#' base2float(tests)
#' # [1] 165.0000 0.0000 165.2500 -165.0000 -165.2500 495.3594
base2float <- function(s, base = 2L) {
# ensure the strings seem logical:
# - start with "-", "+", or "[01]"
# - zero or more "[01]"
# - optional decimal "." (can easily change to "," for alternate reps)
# - zero or more "[01]"
stopifnot(all(grepl("^[-+]?[01]*\\.?[01]*$", s)))
splits <- strsplit(s, "\\.")
wholes <- sapply(splits, `[[`, 1L)
wholes[wholes %in% c("", "-", "+")] <- paste0(wholes[wholes %in% c("", "-", "+")], "0")
fracs <- sapply(splits, `[`, 2L)
fracs[is.na(fracs)] <- "0"
# because string-length is used in our calcs ...
fracs <- gsub("0+$", "0", fracs)
whole10 <- strtoi(wholes, base = base)
frac10 <- strtoi(fracs, base = base) / (base^nchar(fracs))
whole10 + sign(whole10)*frac10
}