C bitwise operator and if statement converted into Swift? - ios

I am working with the following C statement, and trying to convert it over to Swift:
if (c1 & c2 & c3 & c4 & c5 & 0xf000)
I am not very familiar with C, so I'm not exactly sure what the if statement is checking, but c1, c2, c3, c4, & c5 are integers, and I know that "&" is a bitwise operator. How could I implement this same statement in Swift?

In C (if I recall correctly), if the result of the paranthesised expression c1 & c2 & ... evaluates to a non-zero value, then that is considered "true".
In Swift, type safety being important, the result of bitwise operations are not automatically cast to a truth value (the Bool type), so you'd need to something like
if c1 & c2 != 0 {
// do this
}

You're probably looking for something like below:
let c1: UInt16 = 0x110F
let c2: UInt16 = 0x1101
let c3: UInt16 = 0x1401
let c4: UInt16 = 0x0001
let c5: UInt16 = 0x0A01
if c1 & c2 & c3 & c4 & c5 & 0xF000 != 0 {
println("Do Something, because some bits lined up!")
}
Swift bitwise operators are described here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html
Bitwise operators are the same in both C and Swift. In C that statement is checking to see if there is at least one bit position that each variable (and the literal) have in common where there is a '1' value. Those common ‘1’ positions are dropped into the new value. 11001 & 10101 would drop into 10001, for instance.
The resultant in both languages is (essentially) an integer. The real difference between C and Swift here is that in C any value that is not ‘0’ can be interpreted as the boolean true. Your C code snippet is doing just that; interpreting a non-zero value as true. Swift, on the other hand differentiates between an integer and a boolean, and requires specificity. That is why in my Swift snippet you have to specifically check for a value that is non-zero.
BTW, you could change your c snippet to what I have below and have the logical equivalent, as well as match the Swift snippet.
if ( (c1 & c2 & c3 & c4 & c5 & 0xf000) != 0)
Hope that was at least a little helpful.

Related

Custom formula in conditional formatting rule sometimes works wrong

I am using the formula = C2 + B2 <> A2 to highlight the cells where this condition is true. For some reason, this formula does not work correctly in some cells. For example, in cells C1, C17.
Please understand the reason.
All numbers in columns A through C are integers.
Your formula is using relative references, but not the right ones. In row 1 you want to compare the values in row 1, in row 2 values of same row and so on.
In your image you've selected C1 and the rule there should be = C1 + B1 <> A1, not = C2 + B2 <> A2
C1 is being highlighted because C2 + B2 is not equal to A2. 12115+460=12575, which is different from 12573.
Same for C17. Your conditional formula is looking 1 row below. Try using
= C1 + B1 <> A1

Reversing Bits in F#

I need help reversing bits in F# as done in this question Reverse bits in number. I'm new to F# and was wondering how we can do this?
let bitreverse x =
let mutable b = 0
while x do
b >>>= 1
b|= x & 1
x >>>= 1
b
I'm not even sure the syntax is correct here. I am very knew to this language.
The direct translation into F# looks like this:
let bitreverse x =
let mutable x = x
let mutable b = 0
while x <> 0 do
b <- b <<< 1
b <- b ||| (x &&& 1)
x <- x >>> 1
b
This is highly imperative with mutable values and this isn't usually how we'd tend to go about writing code in F#. Notice that re-assignment of a mutable variable is a little different to what you might be used to in an imperative language, you have to use <- which is called the destructive update operator.
Thankfully, it's pretty straightforward to translate this into a recursive function that uses immutable values which should be a little more idiomatic
let bitreverse2 x =
let rec bitRerverseHelper b x =
match x with
|0 -> b // if 0, the recursion stops here and we return the result: b
|_ -> bitRerverseHelper ((b <<< 1) ||| (x &&& 1)) (x >>> 1) // otherwise recurse
bitRerverseHelper 0 x
F# doesn't support compound assignment, so you can't do something like b |= x & 1, you need to expand it to b <- b ||| (x &&& 1).
The argument x isn't mutable, so you need to create a local binding and mutate that. It looks weird, but you can just write let mutable x = x as the first line of your function to shadow the existing binding with a mutable one.
x is an int, not a bool, so you can't use it as the condition for your while loop. Use x <> 0 instead.
Indentation matters in F#, so make sure that while and your final b both line up with the first let.
Fixing those issues will make your code work, but idiomatic F# would probably forgo the while loop and mutation and use a recursive inner function with an accumulator instead.

Cartesian product in Z3

I have two different sets for example {e1, e2, e3} type of E1 and {g1, g2, g3} type of E2 which defined as follows:
E1 = DeclareSort('E1')
e1,e2,e3 = Consts('e1 e2 e3', E1)
E2 = DeclareSort('E2')
g1,g2,g3 = Consts('g1 g2 g3', E2)
My question is how can I make Z3 give me a Cartesian product between the two sets. I need the result like following:
{(e1, g1),(e1, g2),(e1, g3),(e2, g1),(e2, g2),(e2, g3),(e3, g1),(e3, g2),(e3, g3)}.
Anyone can help?
Thanks
Note that e1,e2, e3, g1, g2, g3 are variables. They are not different by definition. So, the assertion e1 == e2 is satisfiable.
You can create products in Python in the usual way:
[(x,y) for x in [e1,e2,e3] for y in [g1,g2,g3]]
If you want to create the product of two sorts, you can use algebraic data-types.
Declare a datatype "Tuple"
>>> Tuple = Datatype('Tuple')
>>> Tuple.declare('mk_tuple', (('first', E1), ('second', E2)))
>>> Tuple = CreateDatatypes(Tuple)[0]
>>> Tuple.mk_tuple(e1, g1)
mk_tuple(e1, g1)
Maybe you're looking for itertools.product()?
>>> import itertools
>>> for x in itertools.product(['e1', 'e2', 'e3'], ['g1', 'g2', 'g3']):
... print(x)
...
('e1', 'g1')
('e1', 'g2')
('e1', 'g3')
('e2', 'g1')
('e2', 'g2')
('e2', 'g3')
('e3', 'g1')
('e3', 'g2')
('e3', 'g3')
>>>

Function return bad value based on parameter (Z3, Python)

I am emulating an array with simple function (Tab) and it doesn't work as expected. If I code it in SMT2, it works well, but in Z3py it doesn't work.
from z3 import *
A = BitVec('A', 8)
B1 = BitVec('B1', 8)
B2 = BitVec('B2', 8)
B3 = BitVec('B3', 8)
B4 = BitVec('B4', 8)
# Emulate Array
def Tab(N):
if N == 0x01: return B1
if N == 0x02: return B2
if N == 0x03: return B3
if N == 0x04: return B4
s = Solver()
s.add(A == 0x01)
s.add(Tab(A + 0x02) == 0x09 )
s.check()
m = s.model()
print (m)
print("Pos:", m.eval(A + 0x02))
print("Tab(3a):", m.eval(Tab(A + 0x02)))
print("Tab(3):", m.eval(Tab(0x03)))
print("B1: ", m[B1])
print("B2: ", m[B2])
print("B3: ", m[B3])
print("B4: ", m[B4])
print("B3n:", m.eval(B3))
Output:
[B1 = 9, A = 1] <- Model
Pos: 3 <- this is OK
Tab(3a): 9 <- this is OK (based on our condition)
Tab(3): B3 <- why does this return name B3? (should return None or 9)
B1: 9 <- this is BAD, here should be None
B2: None
B3: None <- this is BAD, here should be 9
B4: None
B3n: B3 <- why does this return name B3?! (should return None or 9)
From the output we see that Tab always returns B1 for parameter 0x03 instead of B3. It looks like A + 0x02 is calculated as 0x01 where it's used as a parameter. Am I doing something wrong, or is it some Z3py implementation error? Or does this have to do with how BitVec terms work?
This looks like the same problem as in this post: How to correctly use Solver() command in Python API of Z3 with declared function.
The problem is that if N == 0x01: ... does not create a Z3 if-then-else expression; it literally check whether N is a Python-int with concrete value 1. To get the desired expression you need to use Z3's If(...) function.

Built-in compare on discriminated unions in f#

In answering this question, I discovered the following behaviour of compare on discriminated unions.
type T = A | B | C | D
compare A B (* val it : int = -1 *)
compare A C (* val it : int = -2 *)
compare A D (* val it : int = -3 *)
I was surprised by this.
Can I rely on compare measuring the "distance" between constructors like this?
The spec says (p. 154) about the generated compareTo:
If T is a union type, invoke Microsoft.FSharp.Core.Operators.compare first on the index of the union cases for the two values, and then on each corresponding field pair of x and y for the data carried by the union case. Return the first non-zero result.
From that, I'd expect compare on type T to always give one of -1,0,1 since that's how compare behaves on numeric types. (Right?)
The quote from the specification says that the generated comparison will first compare the tags (that is essentially the index of the constructors), but I'm not sure if this gives you any useful information - because if the union carries some value, you will not know whether the number is distance between the constructors, or the result of the comparison of the contained values. For example:
type Tricky() =
interface System.IComparable with
override x.CompareTo(b) = -2
type DU =
| A of Tricky
| B
| C
// Returns -2 because of the distance between constructors
compare (A (Tricky())) C
// Returns -2 because of the comparison on `Tricky` objects
compare (A (Tricky())) (A(Tricky()))
If you wanted to rely on the ability to get the distance between constructors, it might be safer to use enumerations:
type DU =
| A = 1
| B = 2
| C = 3
Then you can get the distance by converting the values to integers using (int DU.A) - (int DU.C).

Resources