Skip to content

Commit d2c92b8

Browse files
committed
we might as well give a correct answer! (StefanKarpinski)
1 parent d8e001f commit d2c92b8

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

base/intfuncs.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,8 @@ function ndigits0znb(x::Integer, b::Integer)
440440
return d
441441
end
442442

443-
ndigits0znb(x::Unsigned, b::Integer) = ndigits0znb(Signed(x), b)
443+
# do first division before conversion with signed here, which can otherwise overflow
444+
ndigits0znb(x::Unsigned, b::Integer) = ndigits0znb(-signed(fld(x, -b)), b) + (x != 0)
444445
ndigits0znb(x::Bool, b::Integer) = x % Int
445446

446447
# The suffix "pb" stands for "positive base"

test/intfuncs.jl

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,14 @@ end
140140
@test all(n -> n == 1, Base.ndigits0z(true, b) for b in [-20:-2;2:20])
141141
@test all(n -> n == 1, ndigits(x, base=b) for b in [-20:-2;2:20] for x in [true, false])
142142

143-
# with negative bases, we don't support yet unsigned integers which can't be converted to Signed
144-
@test_throws InexactError ndigits(typemax(UInt64), base=-2)
143+
# issue #29148
144+
@test ndigits(typemax(UInt64), base=-2) == ndigits(big(typemax(UInt64)), base=-2)
145+
for T in Base.BitInteger_types
146+
n = rand(T)
147+
b = -rand(2:100)
148+
@test ndigits(n, base=b) == ndigits(big(n), base=b)
149+
end
150+
145151
end
146152
@testset "bin/oct/dec/hex/bits" begin
147153
@test string(UInt32('3'), base = 2) == "110011"

0 commit comments

Comments
 (0)