Here is some functionality to transform integers into lists of 0,1 and the converse:
Did you know ... | Search Documentation: |
Function >>/2 |
A is -3464 >> 100
binds A to -1. If IntExpr2
is negative, a right shift (see >>/2)
is performed with the negated value of IntExpr2.Here is some functionality to transform integers into lists of 0,1 and the converse:
The underlying bit pattern seems to be 2-complement with an infinite number of bits "to the left" (because we can have arbitrarily large numbers):
:- debug(bitshift_them). bitshift_them(How,MaxBits) :- must_be(oneof([neg,pos]),How), must_be(nonneg,MaxBits), ((How==neg) -> Mult = -1 ; Mult = +1), bitshift_them(Mult,1,1,MaxBits). bitshift_them(_,_,Bits,Bits) :- !. bitshift_them(Mult,TwoExpN,Bits,MaxBits) :- Bits < MaxBits,!, P is Mult*TwoExpN, S is P>>1, debug(bitshift_them,"Shifted ~d (~d bits) 'rightwards' by ~d to get ~d",[P,Bits,1,S]), ((Mult > 0) -> assertion(((P == 1, S == 0); 2*S =:= P)) ; assertion(((P == -1, S == -1); (P == -2, S == -1); (2*S =:= P))) ), BitsNext is Bits+1, TwoExpNNext is TwoExpN*2, bitshift_them(Mult,TwoExpNNext,BitsNext,MaxBits).
Then:
?- bitshift_them(pos,100). % Shifted 1 (1 bits) 'rightwards' by 1 to get 0 % Shifted 2 (2 bits) 'rightwards' by 1 to get 1 % Shifted 4 (3 bits) 'rightwards' by 1 to get 2 % Shifted 8 (4 bits) 'rightwards' by 1 to get 4 % Shifted 16 (5 bits) 'rightwards' by 1 to get 8 ... % Shifted 39614081257132168796771975168 (96 bits) 'rightwards' by 1 to get 19807040628566084398385987584 % Shifted 79228162514264337593543950336 (97 bits) 'rightwards' by 1 to get 39614081257132168796771975168 % Shifted 158456325028528675187087900672 (98 bits) 'rightwards' by 1 to get 79228162514264337593543950336 % Shifted 316912650057057350374175801344 (99 bits) 'rightwards' by 1 to get 158456325028528675187087900672 true.
?- bitshift_them(neg,100). % Shifted -1 (1 bits) 'rightwards' by 1 to get -1 % Shifted -2 (2 bits) 'rightwards' by 1 to get -1 % Shifted -4 (3 bits) 'rightwards' by 1 to get -2 % Shifted -8 (4 bits) 'rightwards' by 1 to get -4 % Shifted -16 (5 bits) 'rightwards' by 1 to get -8 ... % Shifted -39614081257132168796771975168 (96 bits) 'rightwards' by 1 to get -19807040628566084398385987584 % Shifted -79228162514264337593543950336 (97 bits) 'rightwards' by 1 to get -39614081257132168796771975168 % Shifted -158456325028528675187087900672 (98 bits) 'rightwards' by 1 to get -79228162514264337593543950336 % Shifted -316912650057057350374175801344 (99 bits) 'rightwards' by 1 to get -158456325028528675187087900672 true.