Big intergers to 32 or 64 bits

Hi Exploratory Team.

I use the below function to transform integers to bits and till now this function has been working very well.

purrr::flatten_chr(purrr::map(., function(x){
str_c(as.integer (intToBits (x)[1:32]), collapse = β€œβ€)

the problem is when I type numbers like 2621380375 I receive an overflow.

I only will work with positive numbers and a bigger integer will is 3999999999.

Can you give me a tiip how to solve it?. thanks.

Since you only use positive integers and go up to only below 2^32, and intToBits() takes the input as a signed integer, you are short of making it work only by one bit.
One way I could think of was prepending the least significant bit separately to the rest of the 31 bits. (The 32nd bit is always 0, since it’s the sign bit and you only use positive values)
How about replacing the content of your function with something like the following?

str_c(c(x%%2, as.integer(intToBits (x/2)[1:31])), collapse = "")

Here is my test result.

> (function(x){str_c(c(x%%2, as.integer(intToBits (x/2)[1:31])), collapse = "")})(3999999997)
[1] "10111111111001001101011001110111"
> (function(x){str_c(c(x%%2, as.integer(intToBits (x/2)[1:31])), collapse = "")})(3999999998)
[1] "01111111111001001101011001110111"
> (function(x){str_c(c(x%%2, as.integer(intToBits (x/2)[1:31])), collapse = "")})(3999999999)
[1] "11111111111001001101011001110111"

Thank You Hideaki, it works smoothly.

1 Like