Convert decimal to IEEE-754 in R

[This article was first published on Statistic on aiR, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

For some theory on the standard IEEE-754, you can read the Wikipedia page. Here I will post only the code of the function to make the conversion in R.


First we write some functions to convert decimal numbers to binary numbers:


decInt_to_8bit

For example, in 8-bit:


decInt_to_8bit(11, 8)
[1] 0 0 0 0 1 0 1 1


devDec_to_8bit(0.625, 8)
[1] 1 0 1 0 0 0 0 0


devDec_to_8bit(0.3, 8)
[1] 0 1 0 0 1 1 0 0
devDec_to_8bit(0.3, 16)
[1] 0 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0

We can delete the extra-zeros from the vectors, using these functions:


remove.zero.aft

So we have:


remove.zero.bef(decInt_to_8bit(11, 8))
[1] 1 0 1 1

remove.zero.aft(devDec_to_8bit(0.625, 8))
[1] 1 0 1

Binding these functions, we have:


dec.to.nbit

Example:


dec.to.nbit(11.625,8)
[1] "1011.101"


Now we can write the code for the decimal to IEEE-754 single float conversion in R:


dec.to.ieee754

The numbers 11.625 and 11.33 in IEEE-754 are:


dec.to.ieee754(11.625)
[1] "01000001001110100000000000000000"

dec.to.ieee754(11.33)
[1] "01000001001101010100011110101110"

You can verify the output with this Online Binary-Decimal Converter

To leave a comment for the author, please follow the link and comment on their blog: Statistic on aiR.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)