RosettaCodeData/Task/Set-right-adjacent-bits/Phix/set-right-adjacent-bits-3.phix
2026-02-01 16:33:20 -08:00

20 lines
584 B
Text

with javascript_semantics
include mpfr.e
function mpz_srb(string input, integer n)
string res = input
mpz tmp = mpz_init("0b"&input),
mask = mpz_init(power(2,n+1)-1),
rask = mpz_init() -- (mask res)
for i=length(input) to 1 by -1 do
if input[i]='0' then
mpz_and(rask,tmp,mask)
if mpz_cmp_si(rask,0)!=0 then
res[i] = '1'
end if
end if
mpz_fdiv_q_2exp(tmp, tmp, 1) -- aka right shift
end for
return res
end function
--...
printf(1,"n = %d: %s\n",{n,mpz_srb(input,n)})