Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a binary string to an integer or a float?

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?

like image 470
BAR Avatar asked Dec 01 '10 20:12

BAR


People also ask

Can you convert string to int or float?

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.

How do you convert binary to float?

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.

How do you convert a string to a float?

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.

Which function converts a string to integer or float value?

parseFloat() The parseFloat() function parses a string argument and returns a floating point number.


1 Answers

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.
like image 135
YOUR ARGUMENT IS VALID Avatar answered Oct 09 '22 18:10

YOUR ARGUMENT IS VALID