按位与到位模运算符 [英] Bitwise and in place of modulus operator

查看:164
本文介绍了按位与到位模运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,两个功率的例子模可以pssed这样EX $ P $:

We know that for example modulo of power of two can be expressed like this:

  x % 2 inpower n == x & (2 inpower n - 1).

例如:

x % 2 == x & 1
x % 4 == x & 3
x % 8 == x & 7 

那么两个数字的一​​般非电力?

What about general nonpower of two numbers?

让我们说:

X%7 ==?

推荐答案

首先,它实际上是不准确的说,

First of all, it's actually not accurate to say that

x % 2 == x & 1

简单的反例: X = -1 。在许多语言,包括Java, 1%2 == -1 。也就是说,不一定模的传统的数学定义。 Java调用它的余运算符为例。

Simple counterexample: x = -1. In many languages, including Java, -1 % 2 == -1. That is, % is not necessarily the traditional mathematical definition of modulo. Java calls it the "remainder operator", for example.

至于按位优化,只能模两可轻松在按位算术做的权力。一般来说,基础的的B仅模权力的可以轻松地与基地的乙做的数字再presentation。

With regards to bitwise optimization, only modulo powers of two can "easily" be done in bitwise arithmetics. Generally speaking, only modulo powers of base b can "easily" be done with base b representation of numbers.

在基地10,例如,对于非负 N N模10 ^氏/ code>只是走最低显著 K 的数字。

In base 10, for example, for non-negative N, N mod 10^k is just taking the least significant k digits.

  • JLS 15.17.3 Remainder Operator %
  • Wikipedia/Modulo Operation

这篇关于按位与到位模运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆