可逆的“二进制转数字";谓词 [英] reversible "binary to number" predicate

查看:7
本文介绍了可逆的“二进制转数字";谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以可逆方式将二进制位(例如,它可能是 0/1 的列表)转换为数字的最佳方法是什么.我在 swi 中写了一个本地谓词,但有更好的解决方案吗?最好的问候

What is the best way to convert binary bits (it might be a list of 0/1, for example) into numbers in a reversible way. I've written a native predicate in swi, but is there better solution ? Best regards

推荐答案

使用CLP(FD)约束,例如:

Use CLP(FD) constraints, for example:

:- use_module(library(clpfd)).

binary_number(Bs0, N) :-
        reverse(Bs0, Bs),
        foldl(binary_number_, Bs, 0-0, _-N).

binary_number_(B, I0-N0, I-N) :-
        B in 0..1,
        N #= N0 + B*2^I0,
        I #= I0 + 1.

查询示例:

?- binary_number([1,0,1], N).
N = 5.

?- binary_number(Bs, 5).
Bs = [1, 0, 1] .

?- binary_number(Bs, N).
Bs = [],
N = 0 ;
Bs = [N],
N in 0..1 ;
etc.

这篇关于可逆的“二进制转数字";谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆