Write Julia functions to convert decimal numbers—both integer or fractional—into their binary representation.
This is working to about 64 bits.
# converts the fractional part of a decimal number (i.e., less than 1)
# into its binary form. Number must be <1 and >2^-64.
function fracdec2bin(n)
nbits = 64;
global b=zeros(Int,nbits);
k=0;
while n != 2.0^-k && k < nbits
k+=1;
if n-2.0^-k > 0
n=n-2.0^-k
b[k]=1
end
end
if n == 2.0^-k
b[k]=1
end
"0."*join(string.(b))
end
function intdec2bin(n)
nbits = 63;
global b=zeros(Int,nbits);
global k=nbits;
while n != 2^k && k > 0
if n-2^k >= 0
n=n-2^k
b[nbits-k]=1
end
k-=1;
end
if n == 2^k
b[nbits-k]=1
elseif k == 1
b[nbits]=1
end
join(string.(b))
end