Skip to content

Commit

Permalink
fix digits(n::Unsigned) with neg base for n > typemax(n)÷2
Browse files Browse the repository at this point in the history
Alternative based on #29187
  • Loading branch information
StefanKarpinski committed Sep 15, 2018
1 parent e2c9878 commit 0499528
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -744,17 +744,25 @@ julia> digits!([2,2,2,2,2,2], 10, base = 2)
```
"""
function digits!(a::AbstractVector{T}, n::Integer; base::Integer = 10) where T<:Integer
base < 0 && isa(n, Unsigned) && return digits!(a, convert(Signed, n), base = base)
2 <= abs(base) || throw(ArgumentError("base must be ≥ 2 or ≤ -2, got $base"))
hastypemax(T) && abs(base) - 1 > typemax(T) &&
throw(ArgumentError("type $T too small for base $base"))
for i in eachindex(a)
if base > 0
a[i] = rem(n, base)
n = div(n, base)
else
a[i] = mod(n, -base)
n = cld(n, base)
isempty(a) && return a

if base > 0
for i in eachindex(a)
n, d = divrem(n, base)
a[i] = d
end
else
# manually peel one loop iteration for type stability
n, d = fldmod(n, -base)
a[firstindex(a)] = d
n = -signed(n)
for i in firstindex(a)+1:lastindex(a)
n, d = fldmod(n, -base)
a[i] = d
n = -n
end
end
return a
Expand Down

0 comments on commit 0499528

Please sign in to comment.