Is the right-shift operator in Objective C on OSX/iOS an arithmetic or logical right shift?
Is the right-shift operator in Objective C on OSX/iOS an arithmetic or logical right shift?
I can't find any references that specify whether the right-shift is arithmetic or logical, or if it varies depen开发者_JAVA技巧ding on the data type (signed/unsigned) and/or architecture (x86/PPC/x64/ARM).
"Programming in Objective-C 2.0" states that this is effectively undefined, but that conflicts with information I've seen elsewhere that compilers attempt to "do the right thing" based on signed-ness of types.
Objective-C does not define the behavior for the right-shift operator. That operator is defined in C. Here's the relevant part of the ANSI C spec:
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
So yes, right-shift operator on a negative number is implementation-defined according to the spec.
I did a quick experiment in the iOS simulator, with the following fragment:
int i = -600; for (int j = 0; j < 68; j++) { NSLog(@"j: %d i: %d", j, i); i = i >> 1; }
Which yielded the result:
j: 0 i: -600
j: 1 i: -300
j: 2 i: -150
j: 3 i: -75
j: 4 i: -38
j: 5 i: -19
j: 6 i: -10
j: 7 i: -5
j: 8 i: -3
j: 9 i: -2
j: 10 i: -1
j: 11 i: -1
...
This would seem to indicate that the shift is arithmetic, not logical, because the sign of the answer is preserved.
精彩评论