Which is correct - '+' or '|' in objective-c? - objective-c

I've seen both of these notations in various threads and I'd like to know which is correct?
Or, is there no functional difference?
return UIInterfaceOrientationMaskPortrait + UIInterfaceOrientationMaskPortraitUpsideDown;
or
return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;

As others have stated, | is the correct operator to use for bitfields.
While other operators might work and yield similar results it is semantically wrong to use them and confusing for other programmers reading your code.
Using + (or ^ which has a similar effect in this case) just obfuscates the meaning. In a code review I would reject it.

The '|' is better
For the purpose of combining bit mask flags, they are almost the same. You have:
0 + 0 = 0
0 | 0 = 0
0 + 1 = 1
0 | 1 = 1
1 + 0 = 1
1 | 0 = 1
However, they are different when you do:
1 + 1 = 0 // and 1 goes to higher bit
1 | 1 = 1
You can have a '1 + 1' case, when you combine same flags. It can happen by mistake, when you modify existing mask, or when you do something less trivial, say you get those flags by calling other methods, then you accumulate them in some variable, and it is possible to get the same flag several times.
In this case, only | gives correct results, so I say that it is better to get a habit of always using |.
It would also make your code more readable by others.

They are both have the same result in this particular case, but | is preferred because it's a more correct operator for bitfields where arithmetic is possible but usually meaningless.
For example, if you have the interface orientation in a variable and you want to enable or disable a particular value, using + can lead to unexpected behavior.
UIInterfaceOrientationMask mask = UIInterfaceOrientationMaskPortrait;
// some other code ...
// Now I want to (incorrectly!) enable portrait, without checking it first
mask = mask + UIInterfaceOrientationMaskPortrait;
// mask now counterintuitively == UIInterfaceOrientationMaskPortraitUpsideDown
If instead you user |, you can ensure that you are operating correctly on the bit field:
UIInterfaceOrientationMask mask = UIInterfaceOrientationMaskPortrait;
// ...
// Now I want to (correctly!) enable portrait, without checking it first
mask = mask | UIInterfaceOrientationMaskPortrait; // mask is what you would expect it to be.

Related

Testing with a metaoperator doesn't print the test description

I was writing tests on Complex arrays and I was using the Z≅ operator to check whether the arrays were approximately equal, when I noticed a missing test description.
I tried to golf the piece of code to find out the simplest case that shows the result I was seeing. The description is missing in the second test even when I use Num or Int variables and the Z== operator.
use Test;
my #a = 1e0, 3e0;
my #b = 1e0, 3e0;
ok #a[0] == #b[0], 'description1'; # prints: ok 1 - description1
ok #a[^2] Z== #b[^2], 'description2'; # prints: ok 2 -
done-testing;
Is there a simple explanation or is this a bug?
It's just precedence -- you need parens.
== is a binary op that takes a single operand on either side.
The Z metaop distributes its operator to a list on either side.
use Test;
my #a = 1e0, 3e0;
my #b = 1e0, 3e0;
ok #a[0] == #b[0], 'description1'; # prints: ok 1 - description1
ok (#a[^2] Z== #b[^2]), 'description2'; # prints: ok 2 - description2
done-testing;
Without parens, 'description2' becomes an additional element of the list on the right. And per the doc for Z:
If one of the operands runs out of elements prematurely, the zip operator will stop.

Executing all assertions in the same Spock test, even if one of them fails

I am trying to verify two different outputs in the context of a single Spock method that runs multiple test cases of the form when-then-where. For this reason I use two assertions at the then block, as can be seen in the following example:
import spock.lang.*
#Unroll
class ExampleSpec extends Specification {
def "Authentication test with empty credentials"() {
when:
def reportedErrorMessage, reportedErrorCode
(reportedErrorMessage, reportedErrorCode) = userAuthentication(name, password)
then:
reportedErrorMessage == expectedErrorMessage
reportedErrorCode == expectedErrorCode
where:
name | password || expectedErrorMessage | expectedErrorCode
' ' | null || 'Empty credentials!' | 10003
' ' | ' ' || 'Empty credentials!' | 10003
}
}
The code is an example where the design requirement is that if name and password are ' ' or null, then I should always expect exactly the same expectedErrorMessage = 'Empty credentials!' and expectedErrorCode = 10003. If for some reason (presumably because of bugs in the source code) I get expectedErrorMessage = Empty! (or anything else other than 'Empty credentials!') and expectedErrorCode = 10001 (or anything else other than 1003), this would not satisfy the above requirement.
The problem is that if both assertions fail in the same test, I get a failing message only for the first assertion (here for reportedErrorMessage). Is it possible to get informed for all failed assertions in the same test?
Here is a piece of code that demonstrates the same problem without other external code dependencies. I understand that in this particular case it is not a good practice to bundle two very different tests together, but I think it still demonstrates the problem.
import spock.lang.*
#Unroll
class ExampleSpec extends Specification {
def "minimum of #a and #b is #c and maximum of #a and #b is #d"() {
expect:
Math.min(a, b) == c
Math.max(a, b) == d
where:
a | b || c | d
3 | 7 || 3 | 7
5 | 4 || 5 | 4 // <--- both c and d fail here
9 | 9 || 9 | 9
}
}
Based on the latest comment by OP, it looks like a solution different from my previous answer would be helpful. I'm leaving the previous answer in-place, as I feel it still provides useful information related to the question (specifically separating positive and negative tests).
Given that you want to see all failures, and not just have it fail at the first assert that fails, I would suggest concatenating everything together into a boolean AND operation. Not using the && shortcut operator, because it will only run until the first check that does not satisfy the entire operation. I would suggest using the &, so that all checks are made, regardless of any previously failing checks.
Given the max and min example above, I would change the expect block to this:
Math.min(a, b) == c & Math.max(a, b) == d
When the failure occurs, it gives you the following information:
Math.min(a, b) == c & Math.max(a, b) == d
| | | | | | | | | | |
4 5 4 | 5 false 5 5 4 | 4
false false
This shows you every portion of the failing assert. By contrast, if you used the &&, it would only show you the first failure, which would look like this:
Math.min(a, b) == c && Math.max(a, b) == d
| | | | | |
4 5 4 | 5 false
false
This could obviously get messy pretty fast if you have more than two checks on a single line - but that is a tradeoff you can make between all failing information on one line, versus having to re-run the test after fixing each individual component.
Hope this helps!
I think there are two different things at play here.
Having a failing assert in your code will throw an error, which will cease execution of the code. This is why you can't have two failing assertions in a single test. Any line of code in an expect or then block in Spock has an implicit assert before it.
You are mixing positive and negative unit tests in the same test. I ran into this before myself, and I read/watched something about this and Spock (I believe from the creator, Peter Niederwieser), and learned that these should be separated into different tests. Unfortunately I couldn't find that reference. So basically, you'll need one test for failing use cases, and one test for passing/successful use cases.
Given that information, here is your second example code, with the tests separated out, with the failing scenario in the second test.
#Unroll
class ExampleSpec extends Specification {
def "minimum of #a and #b is #c and maximum of #a and #b is #d - successes"() {
expect:
Math.min(a, b) == c
Math.max(a, b) == d
where:
a | b || c | d
3 | 7 || 3 | 7
9 | 9 || 9 | 9
}
def "minimum of #a and #b is #c and maximum of #a and #b is #d - failures"() {
expect:
Math.min(a, b) != c
Math.max(a, b) != d
where:
a | b || c | d
5 | 4 || 5 | 4
}
}
As far as your comment about the MongoDB test case - I'm not sure what the intent is there, but I'm guessing they are making several assertions that are all passing, rather than validating that something is failing.

What is the most elegant way to pick a random value from a set defined in NS_OPTION in objective-c?

I have an NS_OPTION that I'm defining as such :
typedef NS_OPTIONS(NSInteger, PermittedSize) {
SmallSize = 1 << 0,
MediumSize = 1 << 1,
LargeSize = 1 << 2
};
And later I set the values I need :
PermittedSize size = SmallSize | MediumSize;
I'm using it to randomly generate an various objects of small and medium sizes(duh) for a particular level of a game.
What is the best way to go about selecting which size of an object to generate? Meaning, I'd like to choose randomly for each object I'm generating whether it will be one of the 2 options allowed (small and medium in this case). Normally I would use an arc4random function with the range of numbers I need - but in this case, how can it be done with bits? (and then mapped back to the values of the PermittedSize type?
Use the result from arc4random to determine the amount of bit shifting you want to do. Something like this:
int bitShiftAmount = arc4random_uniform(numberOfPermittedSizes);
PermittedSize size = 1 << bitShiftAmount;
You are still working with integers. SmallSize is 1. MediumSize is 2. And LargeSize is 4.
So pick a random number from 1 to 3. 1 is small, 2 is medium, 3 is both.
Once you have a random number, assign it.
NSInteger val = arc4random_uniform(3) + 1; // give 1-3
PermittedSize size = (PermittedSize)val;

I'm new to visual basic and trying to understand how to set individual bits in a byte [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi, I am new to Visual Basic, I have a project where I need to be able to manipulate individual bits in a value.
I need to be able to switch these bits between 1 and 0 and combine multiple occurrences of bits into one variable in my code.
Each bit will represent a single TRUE / FALSE value, so I'm not looking for how to do a single TRUE / FALSE value in one variable, but rather multiple TRUE / FALSE values in one variable.
Can someone please explain to me how I can achieve this please.
Many thanks in advance.
Does it have to be exactly one bit?
Why don't you just use the actual built in VB data type of Boolean for this.
http://msdn.microsoft.com/en-us/library/wts33hb3(v=vs.80).aspx
It's sole reason for existence is so you can define variables that have 2 states, true or false.
Dim myVar As Boolean
myVar = True
myVar = Flase
if myVar = False Then
myVar = True
End If
UPDATE (1)
After reading through the various answers and comments from the OP I now understand what it is the OP is trying to achieve.
As others have said the smallest unit one can use in any of these languages is an 8 bit byte. There is simply no order of data type with a smaller bit size than this.
However, with a bit of creative thinking and a smattering of binary operations, you can refer to the contents of that byte as individual bits.
First however you need to understand the binary number system:
ALL numbers in binary are to the power of two, from right to left.
Each column is the double of it's predecessor, so:
1 becomes 2, 2 becomes 4, 4 becomes 8 and so on
looking at this purely in a binary number your columns would be labelled thus:
128 64 32 16 8 4 2 1 (Remember it's right to left)
this gives us the following:
The bit at position 1 = 1;
The bit at position 2 = 2;
The bit at position 3 = 4;
The bit at position 4 = 8;
and so on.
Using this method on the smallest data type you have (The byte) you can pack 8 bit's into one value. That is you could use one variable to hold 8 separate values of 1 or 0
So while you cannot go any smaller than a byte, you can still reduce memory consumption by packing 8 values into 1 variable.
How do you read and write the values?
Remember the column positions? well you can use something called Bit Shifting and Bit masks.
Bit Shifting is the process of using the
<<
and
>>
operators
A shifting operation takes as a parameter the number of columns to shift.
EG:
Dim byte myByte
myByte = 1 << 4
In this case the variable 'myByte' would become equal to 16, but you would have actually set bit position 5 to a 1, if we illustrate this, it will make better sense:
mybyte = 0 = 00000000 = 0
mybyte = 1 = 00000001 = 1
mybyte = 2 = 00000010 = (1 << 1)
mybyte = 4 = 00000100 = (1 << 2)
mybyte = 8 = 00001000 = (1 << 3)
mybyte = 16 = 00010000 = (1 << 4)
the 0 through to 16 if you note is equal to the right to left column values I mentioned above.
given what Iv'e just explained then, if you wanted to set bits 5, 4 and 1 to be equal to 1 and the rest to be 0, you could simply use:
mybyte = 25(16 + 8 + 1) = 00011001 = (1 << 4) + (1 << 3) + 1
to get your bits back out, into a singleton you just bit shift the other way
retrieved bit = mybyte >> 4 = 00000001
Now there is unfortunately however one small flaw with the bit shifting method.
by shifting back and forth you are highly likely to LOOSE information from any bits you might already have set, in order to prevent this from happening, it's better to combine your bit shifting operations with bit masks and boolean operations such as 'AND' & 'OR'
To understand what these do you first need to understand simple logic principles as follows:
AND
Output is one if both the A and B inputs are 1
Illustrating this graphically
A B | Output
-------------
0 0 | 0
0 1 | 0
1 0 | 0
1 1 | 1
As you can see if a bit position in our input number is a 1 and the same position in our input number B is 1, then we will keep that position in our output number, otherwise we will discard the bit and set it to a 0, take the following example:
00011001 = Bits 5,4 and 1 are set
00010000 = Our mask ONLY has bit 5 set
if we perform
00011001 AND 0010000
we will get a result of
00010000
which we can then shift down by 5
00010000 >> 5 = 00000001 = 1
so by using AND we now have a way of checking an individual bit in our byte for a value of 1:
if ((mybyte AND 16) >> 1) = 1 then
'Bit one is set
else
'Bit one is NOT set
end if
by using different masks, with the different values of 2 in the right to left columns as shown previously, we can easily extract different singular values from our byte and treat them as a simple bit value.
Setting a byte is just as easy, except you perform the operation the opposite way using an 'OR'
OR
Output is one if either the A or B inputs are 1
Illustrating this graphically
A B | Output
-------------
0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 1
eg:
00011001 OR 00000100 = 00011101
as you can see the bit at position 4 has been set.
To answer the fundamental question that started all this off however, you cannot use a data type in VB that has any resolution less than 1 byte, I suspect if you need absolute bit wise accuracy I'm guessing you must be writing either a compression algorithm or some kind of encryption system. :-)
01010100 01110010 01110101 01100101, is the string value of the word "TRUE"
What you want is to store the information in a boolean
Dim v As Boolean
v = True
v = False
or
If number = 84 Then ' 84 = 01010100 = T
v = True
End If
Other info
Technicaly you can't store anything in a bit, the smallest value is a char which is 8 bit. You'll need to learn how to do bitwise operation. Or use the BitArray class.
VB.NET (nor any other .NET language that I know of) has a "bit" data type. The smallest that you can use is a Byte. (Not a Char, they are two-bytes in size). So while you can read and convert a byte of value 84 into a byte with value 1 for true, and convert a byte of value 101 into a byte of value 0 for false, you are not saving any memory.
Now, if you have a small and fixed number of these flags, you CAN store several of them in one of the integer data types (in .NET the largest integer data type is 64 bits). Or if you have a large number of these flags you can use the BitArray class (which uses the same technique but backs it with an array so storage capacity is greater).

Any way to give names to each of a set of successive integers?

I have an int called setupStage. This is simply a value I increment at the completion of each stage, so I can say, if (setupStage == 2), and I know that I am at the third stage (it defaults to 0).
Is there a way I can refer to these numbers in a better way? For example:
if (setupStage == stageEnterName)
Instead of having to refer to its actual raw int value.
It may be a misconception, but does what I am trying to achieve have anything to do with defining macros?
Yes!
Try this:
typedef enum {
MyType0,
MyType1,
MyType2,
MyType3
} MyType;
This is the same thing as this:
typedef enum {
MyType0 = 0,
MyType1,
MyType2,
MyType3
} MyType;
The values default to 0 at the first slot and then increment by 1 automatically. Note that the token names (MyTypeX) are arbitrary string values you set.
In this case they go from 0 to 3. Then you can say something like this:
if (setupStage == MyType3)
Which is identical to
if (setupStage == 3)
It sounds to me like you do want a macro like solution, and fortunately one exists.
STAGE_ONE = 0
STAGE_TWO = 1
STAGE_THREE = 2
# ...
if setupStage == STAGE_THREE:
will work.