user1848601
user1848601

Reputation:

C bitwise operator and if statement converted into Swift?

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?

Upvotes: 2

Views: 1842

Answers (2)

PixelCloudSt
PixelCloudSt

Reputation: 2805

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.

Upvotes: 3

Aky
Aky

Reputation: 1817

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
}

Upvotes: 5

Related Questions