I have binary strings in the form of either:
<<"5.7778345">>
or
<<"444555">>
I do not know before hand whether it will be a float or integer.
I tried doing a check to see if it is an integer. This does not work since it is binary. I alos tried converting binary to list, then check if int or float. I did not have much success with that.
It needs to be a function such as:
binToNumber(Bin) ->
%% Find if int or float
Return.
Anyone have a good idea of how to do this?
We can convert an integer or specific strings into floating-point numbers using the python built-in method called float() method. The float() method takes string or integer data type and converts the given data into a floating-point number.
Converting to Floating pointSet the sign bit - if the number is positive, set the sign bit to 0. If the number is negative, set it to 1. Divide your number into two sections - the whole number part and the fraction part.
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.
parseFloat() The parseFloat() function parses a string argument and returns a floating point number.
This is the pattern that we use:
binary_to_number(B) ->
list_to_number(binary_to_list(B)).
list_to_number(L) ->
try list_to_float(L)
catch
error:badarg ->
list_to_integer(L)
end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With