Skip to content

Commit

Permalink
Fix JuliaLang#14341, rewrite bytes2hex to be more efficient
Browse files Browse the repository at this point in the history
Add hex(x::Vector{UInt8}) & hex(x::ByteString)
  • Loading branch information
ScottPJones committed Dec 14, 2015
1 parent 53978e7 commit 0011392
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 11 deletions.
18 changes: 9 additions & 9 deletions base/floatfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ maxintfloat() = maxintfloat(Float64)

isinteger(x::AbstractFloat) = (trunc(x)==x)&isfinite(x)

num2hex(x::Float16) = hex(reinterpret(UInt16,x), 4)
num2hex(x::Float32) = hex(box(UInt32,unbox(Float32,x)),8)
num2hex(x::Float64) = hex(box(UInt64,unbox(Float64,x)),16)
hex(x::Float16) = hex(reinterpret(UInt16,x), 4)
hex(x::Float32) = hex(box(UInt32,unbox(Float32,x)),8)
hex(x::Float64) = hex(box(UInt64,unbox(Float64,x)),16)

function hex2num(s::AbstractString)
if length(s) <= 8
return box(Float32,unbox(UInt32,parse(UInt32,s,16)))
end
return box(Float64,unbox(UInt64,parse(UInt64,s,16)))
end
num2hex{T<:Union{Float16, Float32, Float64}}(x::T) = hex(x)

hex2num(s::AbstractString) =
(length(s) <= 8
? box(Float32,unbox(UInt32,parse(UInt32,s,16)))
: box(Float64,unbox(UInt64,parse(UInt64,s,16))))

@vectorize_1arg Number abs
@vectorize_1arg Number abs2
Expand Down
2 changes: 1 addition & 1 deletion base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ function hex(x::Unsigned, pad::Int, neg::Bool)
x >>= 4
i -= 1
end
if neg; a[1]='-'; end
neg && (a[1] = '-')
ASCIIString(a)
end

Expand Down
17 changes: 16 additions & 1 deletion base/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -234,4 +234,19 @@ function hex2bytes(s::AbstractString)
return a
end

bytes2hex(arr::Vector{UInt8}) = join([hex(i,2) for i in arr])
function hex(arr::Vector{UInt8})
out = Vector{UInt8}(sizeof(arr)<<1)
o = 0
for i = 1:sizeof(arr)
v = arr[i]
d = v>>4
out[o += 1] = ('0' + d + 39 * (d > 9))
d = v & 0xf
out[o += 1] = ('0' + d + 39 * (d > 9))
end
ASCIIString(out)
end

hex(str::ByteString) = hex(str.data)

bytes2hex(arr::Vector{UInt8}) = hex(arr)

0 comments on commit 0011392

Please sign in to comment.