如何将二进制字符串转换为整数或浮点数? [英] How to convert a binary string to an integer or a float?
问题描述
我有以下两种形式的二进制字符串:
I have binary strings in the form of either:
<<"5.7778345">>
或
<<"444555">>
我事先不知道它将是浮点数还是整数.
I do not know before hand whether it will be a float or integer.
我尝试进行检查以查看它是否为整数.由于它是二进制文件,因此不起作用.我也尝试将二进制文件转换为列表,然后检查int或float.我没有那么成功.
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.
它必须具有以下功能:
binToNumber(Bin) ->
%% Find if int or float
Return.
每个人都有一个很好的主意吗?
Anyone have a good idea of how to do this?
推荐答案
没有快速的方法.改用类似这样的东西:
No quick way to do it. Use something like this instead:
bin_to_num(Bin) ->
N = binary_to_list(Bin),
case string:to_float(N) of
{error,no_float} -> list_to_integer(N);
{F,_Rest} -> F
end.
这应将二进制文件转换为列表(字符串),然后尝试使其适合浮点数.如果无法做到这一点,我们将返回一个整数.否则,我们保留浮点数并将其返回.
This should convert the binary to a list (string), then try to fit it in a float. When that can't be done, we return an integer. Otherwise, we keep the float and return that.
这篇关于如何将二进制字符串转换为整数或浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!