C strange modular operation

So, I have this thing where I got the following operation:

NSInteger articleIndex = self.featuredArticlesCounter % self.featuredArticles.count; 

In this case, self.featuredArticlesCounter is -1 and self.featuredArticles.count is 10

So this is basically -1% 10, which should be 9, but the result is 5.

Google says it.

And if I do NSInteger articleIndex = -1 % 10; he gives me -1

I tried casting NSUInteger from count to NSInteger and it does not work. I tried to insert brackets everywhere, but that didn't work either.

Since then, I switched to using ((-1 % 10) + 10) % 10 .

But I'm still wondering what the deal is. Any ideas?

Edit

featuredArticlesCounter is a signed int

self.featuredArticles.count is an unsigned int

+4
source share
2 answers

featuredArticlesCounter is obviously an unsigned int. When you thought you set it to -1, you really set it to 2**32 - 1 (~ 0). This mod 10 number is 5 . (Apparently 2**(8k)-1 % 10 is 5, so it doesn't matter what size the unsigned actually is)

As for why -1 % 10 is -1 , I believe in C, the mode of negative numbers is determined by the implementation, but in this case (as in Java) it is defined so that x / y + x % y == x . If you insert negative numbers, -1 / 10 + -1 % 10 = -1 -> -1 % 10 = -1 .

+6
source

Perhaps the hardware (or software?) Treats the number as an unsigned integer:

  • -1 == 0xFFFFFFFF (in two compliment encodings)

  • 0xFFFFFFFF == 4294967295 (assuming the raw data is an unsigned integer)

  • 4294967295 % 10 == 5 (trivial to observe the last digit)

That would be my best guess.

+3
source

Source: https://habr.com/ru/post/1499830/


All Articles