Skip to content

Instantly share code, notes, and snippets.

@djnavarro
Created March 3, 2022 06:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djnavarro/b765c5be33a366cbb42959410dbf1ffd to your computer and use it in GitHub Desktop.
Save djnavarro/b765c5be33a366cbb42959410dbf1ffd to your computer and use it in GitHub Desktop.
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