binary or hex representation

I am interested at looking at the underlying binary (or hex) representation of numbers in R. Is there a way, for example, to see what the underlying representation of a double is? Is there a way to supply a binary/hex value and then tell R to regard it as a double?

For 32 bit integers:

i <- 10
# raw vector
paste(rev(as.integer(intToBits(i))), collapse = "")
# remove leading zeroes
as.character(as.integer(paste(rev(as.integer(intToBits(i))), collapse = "")))
# same result

64 bit integers require a slightly different solution.

For non-integers you can use the solution here:
r - Converting non-integer decimal numbers to binary - Stack Overflow

This is definitely helpful, but for floating point numbers doesn't necessarily give you the binary representation. For example, following the link supplied:

[1] "NA.NA"

Why NA ? Why not a float ?

I would like to be able to see how NA is represented. (My understanding is that R uses the standard IEEE representation, but I'd like to see for myself.)

I provided a link for you for floating point numbers.

You did, and I appreciate it. But I would also like to see the representation of a double NA. The linked code won't do that.

I'm kid of surprised there isn't a way to see the hex representation of pretty much anything, but maybe there isn't

A floating point number would be NA, not NA.NA.

Clearly there is something I'm not understanding. Unless I've screwed up, the floatToBin function is what you pointed me at. When I call it with NA I get the result shown. What should I be doing instead?

That was a user-defined function written on SO by somebody to answer a related question to yours. Such questions rarely cover all cases. Indeed the poster stated it did not cover negative numbers. If you want a more comprehensively applicable function you'll either have to search a bit further yourself or just extend the example function to cover any cases like NAs, negative numbers, etc.

I'm sure you're right. I was hoping for an existing function that would show the 16 hex digits of whatever is stored as a double. (And maybe one that would take 16 hex digits and stuff them into a double.) Maybe such a thing doesn't exist.

I did a better Google search than I had before and found which offers the code

Rcpp::cppFunction('void print_hex(double x) {
    uint64_t y;
    static_assert(sizeof x == sizeof y, "Size does not match!");
    std::memcpy(&y, &x, sizeof y);
    Rcpp::Rcout << std::hex << y << std::endl;
}', plugins = "cpp11", includes = "#include <cstdint>")```

This gives


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.