What function f
is f(typeof(x), bitstring(x)) == x
?
f(T, s) = reinterpret(T, parse(Int, s; base = 2))
?
EDIT: This is not general enough (see @rafael.guerra post below). The general answer adopted form @JeffreySarnoff’s solution would look like:
f(T, s) = reinterpret(T, Meta.parse("0b" * s))
2 Likes
Not quite, it seems
f(T, s) = reinterpret(T, parse(Int, s; base = 2))
julia> let x =rand(Float16)
f(typeof(x), bitstring(x)) == x
end
ERROR: bitcast: argument size does not match size of target type
Stacktrace:
[1] reinterpret(#unused#::Type{Float16}, x::Int64)
@ Base ./essentials.jl:438
[2] f(T::Type, s::String)
@ Main ./REPL[1]:1
Fyi, there is a solution in this other post.
2 Likes
I intended to cover this with BitsX.jl
, but found it was missing. I added a method to do this.
You can define the function like this:
test_identity(x) = parse_bin(typeof(x), bitstring(x))
Works for many types, including FloatX
.
parse_bin
is similar to Base.parse(T, s; base=2)
. But it is much faster and also allows filtering out formatting characters:
julia> s = BitsX.randbitstring(64)
"1100101110101110011000111100111000101101111011101010111100101000"
julia> @btime parse(UInt, $s; base=2);
197.869 ns (0 allocations: 0 bytes)
julia> @btime parse_bin(UInt, $s);
53.767 ns (0 allocations: 0 bytes)
2 Likes