如何将二进制字符串转换为整数或浮点数?
我有以下形式的二进制字符串:
<<"5.7778345">>
或者
<<"444555">>
我事先不知道它是浮点数还是整数。
我尝试检查它是否是整数。这不起作用,因为它是二进制的。我也尝试将二进制转换为列表,然后检查是否是 int 或 float。我在这方面并没有取得太大成功。
它需要是一个函数,例如:
binToNumber(Bin) ->
%% Find if int or float
Return.
有人知道如何做到这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有快速的方法来做到这一点。使用类似这样的东西:
这应该将二进制文件转换为列表(字符串),然后尝试将其放入浮点数中。当无法完成时,我们返回一个整数。否则,我们保留浮动并返回它。
No quick way to do it. Use something like this instead:
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.
这是我们使用的模式:
This is the pattern that we use:
自 Erlang/OTP R16B 起,无需中间转换为列表:
Intermediate conversion to list is unnecessary since Erlang/OTP R16B:
binary_to_term
函数及其对应的term_to_binary
可能会很好地为您服务。The
binary_to_term
function and its counterpartterm_to_binary
would probably serve you well.