Created
March 3, 2022 06:00
-
-
Save djnavarro/b765c5be33a366cbb42959410dbf1ffd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
unpack_double <- function(x) { | |
binary <- numToBits(x) # little-endian binary representation | |
structure( | |
list( | |
sign = binary[64], # 1-bit sign | |
exponent = binary[63:53], # 11-bit exponent | |
mantissa = binary[52:1] # 52-bit mantissa | |
), | |
class = "unpacked_double" | |
) | |
} | |
print.unpacked_double <- function(x, ...) { | |
sign <- as.character(as.integer(x$sign)) | |
exponent <- paste(as.character(as.integer(x$exponent)), collapse = "") | |
mantissa <- paste(as.character(as.integer(x$mantissa)), collapse = "") | |
cat(sign, exponent, mantissa, "\n") | |
} | |
repack_double <- function(x) { | |
s <- ifelse(as.integer(x$sign) == 0, 1, -1) | |
p <- sum(as.integer(x$exponent) * 2^(10:0)) - 2^10 + 1 | |
v <- sum(as.integer(x$mantissa) * (2^(-1:(-52)))) + 1 | |
s * v * 2 ^ p | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment