attempt #1
overflow_next <= (op1_shifted(word_width - 1) = op2(word_width - 1)) and (result_var(word_width - 1) /= op2(word_width - 1));
Error (10327): VHDL error at alu.vhd(99): can't determine definition of operator ""="" -- found 0 possible definitions
Error (10327): VHDL error at alu.vhd(99): can't determine definition of operator ""/="" -- found 0 possible definitions
attempt #2
overflow_next <= ((op1_shifted(word_width - 1) = '0') and (op2(word_width - 1) = '0') and (result_var(word_width - 1) = '1')) or ((op1_shifted(word_width - 1) = '1') and (op2(word_width - 1) = '1') and (result_var(word_width - 1) = '0'));
Error (10327): VHDL error at alu.vhd(99): can't determine definition of operator ""="" -- found 0 possible definitions
All signals and variables are std_logic_vector except word_width which is an integer generic. What's the problem here? I can compare standalone std_logic signals but not parts of std_logic_vector signals? Is there any workaround if what I'm trying to do is impossible?
I suspect the error report is misleading and you need to properly construct a conditional signal assignment statement, such as:
overflow_next <= '1' when (op1_shifted(word_width - 1) = op2(word_width - 1)) and (result_var(word_width - 1) /= op2(word_width - 1)) else '0';
Related
I have this code in Pine script for tradingview:
if close >= base_bar_low and close <= base_bar_high
//Check for one or more neighboring bars within 50-50 range of Stochastic or Williams %R
i := 0
for i in range(2, stoch_length + 1):
if (stoch_D[i] <= 50) and (stoch_D[i] >= 50) or (willR[i] >= -50) and (willR[i] <= 50):
//Check for last bar close within 30% of base bar's high
last_bar_high = high[1] + (atr * 0.3)
if close <= last_bar_high:
plot("W1-Long")
end
and I have this error: 'i' is not a valid type keyword in variable declaration - how can I avoid it?
I have a program with logic as described in the pseudocode below. x is a string, and x[k] will return the decimal charcode of character at index k. The ^ operator returns the decimal XOR result of the operands.
x = input
int checksum = x[0] ^ x[1] ^ x[2]
int sum = 0
sum += x[36] ^ x[23] == 111
sum += x[23] ^ x[29] == 101
sum += x[29] ^ x[30] == 116
sum += x[30] ^ x[9] == 115
sum += x[9] ^ x[25] == 0
return sum == checksum and x[0] ^ x[29] == 100 and x[1] ^ x[30] == 200
I want to find input that makes this program return true. If I want to solve this problem in Z3Py, is there a way for me to do it? I need some K out of N constraint that allows me to express the constraints as expressions, but I haven't found support for this.
Psedocode for what I would like to do with Z3:
int checksum = x[0] ^ x[1] ^ x[2]
bools = []
bools.append(Bool(x[36] ^ x[23] == 111))
bools.append(Bool(x[23] ^ x[29] == 101))
bools.append(Bool(x[29] ^ x[30] == 116))
bools.append(Bool(x[30] ^ x[9] == 115))
bools.append(Bool(x[9] ^ x[25] == 0))
state.add(bools[0])
state.add(bools[1])
state.add(bools[2])
state.add(bools[3])
state.add(bools[4])
state.add(x[0] ^ x[29] == 100)
state.add(x[1] ^ x[30] == 200)
state.add(PbEq([boolean for boolean in bools], checksum))
Reading your problem description, I don't see why you need K-out-of-N constraints for this problem. It seems like a straightforward encoding using bit-vector theory. But perhaps I didn't quite understand the problem you're trying to solve. It'd help to show what you tried, and what failed.
In any case, if you really need K-out-of-N constraints, then Z3 has special support for them in various forms:
AtMost
AtLeast
PbEq
PbLe
PbGe
Such constraints are known as "Pseudo-boolean," and hence the Pb prefix.
I am working on some assembly program analysis task using Z3. And I am trapped in simulating the semantics of x86 opcode bsf.
The semantics of bsf operand1 operand2 is defined as searches the source operand (operand1) for the least significant set bit (1 bit).
Its semantics can be simulated in C as:
if(operand1 == 0) {
ZF = 0;
operand2 = Undefined;
}
else {
ZF = 0;
Temporary = 0;
while(Bit(operand1, Temporary) == 0) {
Temporary = Temporary + 1;
operand2 = Temporary;
}
}
Right now, suppose each operand (e.g., register) maintains a symbolic expression, I am trying to simulate the above semantics in Z3Py. The code I wrote is something like this (simplified):
def aux_bsf(x): # x is operand1
if simplify(x == 0):
raise Exception("undefined in aux_bsf")
else:
n = x.size()
for i in range(n):
b = Extract(i, i, x)
if simplify(b == 1):
return BitVecVal(i, 32)
raise Exception("undefined in bsf")
However, I find that the evaluation of simplify(x==0) (e.g., x equals BitVecVal(13, 32) + BitVec("symbol1", 32),) is always equal to True. In other words, I am always trapped in the first exception!
Am I doing anything wrong here..?
====================================================
OK, so I think what I need is something like:
def aux_bsf(x):
def aux(x, i):
if i == 31:
return 31
else:
return If(Extract(i, i, x) == 1, i, aux(x, i+1))
return aux(x, 0)
simplify(x == 0) returns an expression, it does not return True/False, where False = 0. Python would treat an expression reference as a non-zero value and therefore take the first branch. Unless 'x' is a bit-vector constant, simplification would not return a definite value. The same issue is with simplify(b == 1).
You could encode such functions as a relation between operand1 and operand2, e.g., something along the lines of:
def aux_bsf(s, x, y):
for k in range(x.size()):
s.Add(Implies(lsb(k, x), y == k)
def lsb(k, x):
first0 = True
if k > 0:
first0 = Extract(x, k-1,0) == 0
return And(Extract(x,k,k) == 1, first0)
You can also use uninterpreted functions for the cases where aux_bsf is under-specified.
For example:
def aux_bsf(x):
bv = x.sort()
bsf_undef = Function('bsf-undef', bv, bv)
result = bsf_undef(x)
for k in reverse(range(bv.size()))
result = If(Extract(x, k, k) == 1), BitVecVal(k, bv), result)
return result
def reverse(xs):
....
I'm trying to translate a code from C to Lua and I'm facing a problem.
How can I translate a Bitwise AND in Lua?
The source C code contains:
if ((command&0x80)==0)
...
How can this be done in Lua?
I am using Lua 5.1.4-8
Implementation of bitwise operations in Lua 5.1 for non-negative 32-bit integers
OR, XOR, AND = 1, 3, 4
function bitoper(a, b, oper)
local r, m, s = 0, 2^31
repeat
s,a,b = a+b+m, a%m, b%m
r,m = r + m*oper%(s-a-b), m/2
until m < 1
return r
end
print(bitoper(6,3,OR)) --> 7
print(bitoper(6,3,XOR)) --> 5
print(bitoper(6,3,AND)) --> 2
Here is a basic, isolated bitwise-and implementation in pure Lua 5.1:
function bitand(a, b)
local result = 0
local bitval = 1
while a > 0 and b > 0 do
if a % 2 == 1 and b % 2 == 1 then -- test the rightmost bits
result = result + bitval -- set the current bit
end
bitval = bitval * 2 -- shift left
a = math.floor(a/2) -- shift right
b = math.floor(b/2)
end
return result
end
usage:
print(bitand(tonumber("1101", 2), tonumber("1001", 2))) -- prints 9 (1001)
Here's an example of how i bitwise-and a value with a constant 0x8000:
result = (value % 65536) - (value % 32768) -- bitwise and 0x8000
In case you use Adobe Lightroom Lua, Lightroom SDK contains LrMath.bitAnd() method for "bitwise AND" operation:
-- x = a AND b
local a = 11
local b = 6
local x = import 'LrMath'.bitAnd(a, b)
-- x is 2
And there are also LrMath.bitOr(a, b) and LrMath.bitXor(a, b) methods for "bitwise OR" and "biwise XOR" operations.
This answer is specifically for Lua 5.1.X
you can use
if( (bit.band(command,0x80)) == 0) then
...
in Lua 5.3.X and onwards it's very straight forward...
print(5 & 6)
hope that helped 😉
This scripting language doesn't have a % or Mod(). I do have a Fix() that chops off the decimal part of a number. I only need positive results, so don't get too robust.
Will
// mod = a % b
c = Fix(a / b)
mod = a - b * c
do? I'm assuming you can at least divide here. All bets are off on negative numbers.
a mod n = a - (n * Fix(a/n))
For posterity, BrightScript now has a modulo operator, it looks like this:
c = a mod b
If someone arrives later, here are some more actual algorithms (with errors...read carefully)
https://eprint.iacr.org/2014/755.pdf
There are actually two main kind of reduction formulae: Barett and Montgomery. The paper from eprint repeat both in different versions (algorithms 1-3) and give an "improved" version in algorithm 4.
Overview
I give now an overview of the 4. algorithm:
1.) Compute "A*B" and Store the whole product in "C" that C and the modulus $p$ is the input for that algorithm.
2.) Compute the bit-length of $p$, say: the function "Width(p)" returns exactly that value.
3.) Split the input $C$ into N "blocks" of size "Width(p)" and store each in G. Start in G[0] = lsb(p) and end in G[N-1] = msb(p). (The description is really faulty of the paper)
4.) Start the while loop:
Set N=N-1 (to reach the last element)
precompute $b:=2^{Width(p)} \bmod p$
while N>0 do:
T = G[N]
for(i=0; i<Width(p); i++) do: //Note: that counter doesn't matter, it limits the loop)
T = T << 1 //leftshift by 1 bit
while is_set( bit( T, Width(p) ) ) do // (N+1)-th bit of T is 1
unset( bit( T, Width(p) ) ) // unset the (N+1)-th bit of T (==0)
T += b
endwhile
endfor
G[N-1] += T
while is_set( bit( G[N-1], Width(p) ) ) do
unset( bit( G[N-1], Width(p) ) )
G[N-1] += b
endwhile
N -= 1
endwhile
That does alot. Not we only need to recursivly reduce G[0]:
while G[0] > p do
G[0] -= p
endwhile
return G[0]// = C mod p
The other three algorithms are well defined, but this lacks some information or present it really wrong. But it works for any size ;)
What language is it?
A basic algorithm might be:
hold the modulo in a variable (modulo);
hold the target number in a variable (target);
initialize modulus variable;
while (target > 0) {
if (target > modulo) {
target -= modulo;
}
else if(target < modulo) {
modulus = target;
break;
}
}
This may not work for you performance-wise, but:
while (num >= mod_limit)
num = num - mod_limit
In javascript:
function modulo(num1, num2) {
if (num2 === 0 || isNaN(num1) || isNaN(num2)) {
return NaN;
}
if (num1 === 0) {
return 0;
}
var remainderIsPositive = num1 >= 0;
num1 = Math.abs(num1);
num2 = Math.abs(num2);
while (num1 >= num2) {
num1 -= num2
}
return remainderIsPositive ? num1 : 0 - num1;
}