How do I convert a binary string to a floating point number?

question
#1

Hello. I’ve been sort of away from Julia for a while and am wanting to get back into things, using version 1.01 (some things changed since 0.6, I see). Figured writing a simple genetic algorithm implementation for myself that would minimize math functions would do the trick (I think there’s libraries for this, already, but this is a ludic exercise) and am having a bit of an issue in order to sort of deal with the genes themselves, seeing as they are represented as strings.

I know I can write an integer and do this to obtain its binary representation as a string, and then I can reconvert it in order to, say, evaluate a function:

image

But I am stumped at how to do that same thing with a floating point number. This is as far as I get:

image

Because I know the parse function doesn’t work in that same way for floats.

Is there some straightforward way of doing this or do I have to write my own conversion function straight from scratch?

Thanks to anybody in advance for anything. Regards.

0 Likes

#2

[Please copy and paste code, instead of pasting screenshots.]

julia> b = 5.0
5.0

julia> s = bitstring(b)
"0100000000010100000000000000000000000000000000000000000000000000"

julia> n = parse(Int, s, base=2)
4617315517961601024

julia> reinterpret(Float64, n)
5.0
1 Like

#3

Welcome back. The current version of Julia is 1.1, so go with that rather than 1.0.1. Julia today is not v0.6, its much cleaner and considerably more refined. At first glance it may look little different; as you write you’ll find good surprises that require reading the docs and looking for similar questions or asking here.

On converting a Float64 or Float32 into and backfrom a bitstring:
The first thing to note is that unlike Int64s and Int32s, floats have an exponent field and a significand field (and a sign bit). Ints are a signbit and all the rest of the bits behave more akin a significand than an exponent. So I’d suggest not using the exponent bits for genetic string elements – certainly not before having become comfortable with using the other float bits.

function float_from_bitstring(::Type{T}, str::String) where {T<:Base.IEEEFloat}
    unsignedbits = Meta.parse(string("0b", str))
    thefloat  = reinterpret(T, unsignedbits)
    return thefloat
end

julia> ϕ = (sqrt(5) + 1) / 2
1.618033988749895

julia> str = bitstring(ϕ)
"0011111111111001111000110111011110011011100101111111010010101000"

julia> float_from_bitstring(Float64, str)
1.618033988749895
4 Likes

#4

Thank you so much to both of you for taking the time.

Julia has certainly changed from 0.6 but it’s also interesting to try to get old code working again. Will upgrade to 1.1 also.

Again: thank you so much.

PD: apologies for pasting the images, bad habit from other places. It will be code next time. Regards.

0 Likes