🤖 作者:包瑞清(richie bao): lastmod: 2024-10-18T20:20:12+08:00

运算类型 说明 Py C C++ C#
算数运算符(Arithmetic operators)

C 系列语言并不支持相除并向下取整和乘方/指数,但 C/C++ 可以通过引入数学库头文件,C# System包含数学类,使用其中的函数或方法实现。Python 不支持++--++自增运算符(操作符)和--自减运算符将给定的数字变化1并返回结果值,其常用于循环迭代中的计数,使用++每次迭代向上计数;使用--每次迭代向下计数。++--运算符可以至于一个值的前后,达到不同的效果。如果将数值至于运算符前,值立即发生改变;如果至于其后,则首先记录其值,然后再变化值。

运算符(Operator) 运算(Operation) Py C C++ C#
+ 加(Addition) ☑️ ☑️ ☑️ ☑️
- 减(Subtraction) ☑️ ☑️ ☑️ ☑️
* 乘(Multiplication) ☑️ ☑️ ☑️ ☑️
/ 除(Division) ☑️ ☑️ ☑️ ☑️
% 模(Modulus) ☑️ ☑️ ☑️ ☑️
// 除并向下取整(Floor Division) ☑️
引入头文件<math.h>,使用函数floor配合/实现

引入头文件<cmath>,使用函数floor配合/实现

使用System命名空间下Math类的方法Math.Floor配合/实现
** 乘方/指数(Exponential/Power) ☑️
引入头文件<math.h>,使用函数pow

引入头文件<cmath>,使用函数pow

使用System命名空间下Math类的方法Math.Pow
++ 自增(Increment)
可以使用+=近似替代
☑️ ☑️ ☑️
-- 自减 (Decrement)
可以使用-=近似替代
☑️ ☑️ ☑️
  a = 10
b = 7

sum_result = a + b
diff = a - b
product = a * b
quotient = a / b
remainder = a % b

print(
    "Sum: %.3f\nDiff: %.3f\nProduct: %.3f\nQuotient: %.3f\nRemainder: %d\n"
    % (sum_result, diff, product, quotient, remainder)
)

e = 10.0
f = 3.0
floorDivision = e // f
print("Floor division of %.2f / %.2f is: %d\n" % (e, f, floorDivision))

base = 2.0
exponent = 3.0
power = base**exponent
print("%.2f raised to the power of %.2f is : %.2f\n" % (base, exponent, power))
  
  🡮
Sum: 17.000
Diff: 3.000
Product: 70.000
Quotient: 1.429
Remainder: 3

Floor division of 10.00 / 3.00 is: 3

2.00 raised to the power of 3.00 is : 8.00
  
  #include <stdio.h>
#include <math.h>

int main() {
	float a = 10, b = 7;
	float sum, diff, product, quotient;
	int remainder;

	sum = a + b;
	diff = a - b;
	product = a * b;
	quotient = a / b;
	remainder = (int)a % (int)b;

	printf("Sum: %.3f\nDiff: %.3f\nProduct: %.3f\nQuotient: %.3f\nRemainder: %d\n", sum, diff, product, quotient, remainder);

	int c = 1, d = 1;
	printf("Postfix increment (c): %d\nPrefix increment (d):%d\n", c++, ++d);
	printf("Postfix increment (c): %d\nPrefix increment (d):%d\n", c++, ++d);

	printf("Postfix decrement (c): %d\nPrefix decrement (d):%d\n", c--, --d);
	printf("Postfix decrement (c): %d\nPrefix decrement (d):%d\n", c--, --d);

	printf("(c): %d\n(d):%d\n", c, d);

	float e = 10., f = 3.;
	int floorDivision;
	floorDivision = floor(e / f);
	printf("Floor division of %.2f / %.2f is: %d\n", e, f, floorDivision);

	double base = 2.0, exponent = 3.0;
	double power;
	power = pow(base, exponent);
	printf("%.2f raised to the power of %.2f is : %.2f\n", base, exponent, power);

	return 0;
}
  
  🡮
Sum: 17.000
Diff: 3.000
Product: 70.000
Quotient: 1.429
Remainder: 3
Postfix increment (c): 1
Prefix increment (d):2
Postfix increment (c): 2
Prefix increment (d):3
Postfix decrement (c): 3
Prefix decrement (d):2
Postfix decrement (c): 2
Prefix decrement (d):1
(c): 1
(d):1
Floor division of 10.00 / 3.00 is: 3
2.00 raised to the power of 3.00 is : 8.00
  
  #include <iostream>
#include <format>
#include <cmath>

int main()
{
	float a = 10, b = 7;
	float sum, diff, product, quotient;
	int remainder;

	sum = a + b;
	diff = a - b;
	product = a * b;
	quotient = a / b;
	remainder = (int)a % (int)b;

	std::cout << std::format("Sum: {:.3f}\nDiff: {:.3f}\nProduct: {:.3f}\nQuotient: {:.3f}\nRemainder: {:d}", sum, diff, product, quotient, remainder) << std::endl;

	int c = 1, d = 1;
	std::cout << std::format("Postfix increment (c): {}\nPrefix increment (d):{}", c++, ++d) << std::endl;
	std::cout << std::format("Postfix increment (c): {}\nPrefix increment (d):{}", c++, ++d) << std::endl;

	std::cout << std::format("Postfix decrement (c): {}\nPrefix decrement (d):{}", c--, --d) << std::endl;
	std::cout << std::format("Postfix decrement (c): {}\nPrefix decrement (d):{}", c--, --d) << std::endl;

	std::cout << std::format("(c) : {}\n(d) : {}", c, d) << std::endl;

	float e = 10., f = 3.;
	int floorDivision = std::floor(e / f);
	std::cout << std::format("Floor division of {:.2f} / {:.2f} is: {:d}", e, f, floorDivision) << std::endl;

	double base = 2.0, exponent = 3.0;
	double power = std::pow(base, exponent);
	std::cout << std::format("{:.2f} raised to the power of {:.2f} is : {:.2f}", base, exponent, power) << std::endl;

	return 0;
}
  
  🡮
Sum: 17.000
Diff: 3.000
Product: 70.000
Quotient: 1.429
Remainder: 3
Postfix increment (c): 1
Prefix increment (d):2
Postfix increment (c): 2
Prefix increment (d):3
Postfix decrement (c): 3
Prefix decrement (d):2
Postfix decrement (c): 2
Prefix decrement (d):1
(c) : 1
(d) : 1
Floor division of 10.00 / 3.00 is: 3
2.00 raised to the power of 3.00 is : 8.00
  
  using System;

class Program
{
    static void Main()
    {
        float a = 10, b = 7;
        float sum, diff, product, quotient;
        int remainder;

        sum = a + b;
        diff = a - b;
        product = a * b;
        quotient = a / b;
        remainder = (int)a % (int)b;

        Console.WriteLine(String.Format("Sum: {0:f3}\nDiff: {1:f3}\nProduct: {2:f3}\nQuotient: {3:f3}\nRemainder: {4:d}", sum, diff, product, quotient, remainder));

        int c = 1, d = 1;
        Console.WriteLine(String.Format("Postfix increment(c): {0:d}\nPrefix increment(d):{1:d}", c++, ++d));
        Console.WriteLine(String.Format("Postfix increment(c): {0:d}\nPrefix increment(d):{1:d}", c++, ++d));

        Console.WriteLine(String.Format("Postfix decrement(c): {0:d}\nPrefix decrement(d):{1:d}", c--, --d));
        Console.WriteLine(String.Format("Postfix decrement(c): {0:d}\nPrefix decrement(d):{1:d}", c--, --d));

        Console.WriteLine(String.Format("(c): {0:d}\n(d):{1:d}", c, d));

        float e = 10, f = 3;
        int floorDivision = (int)Math.Floor(e / f);
        Console.WriteLine(String.Format("Floor division of {0:f2} / {1:f2} is: {2:d}", e, f, floorDivision));

        double baseval = 2, exponent = 3;
        double power = Math.Pow(baseval, exponent);
        Console.WriteLine(String.Format("{0:f2} raised to the power of {1:f2} is : {2:f2}", baseval, exponent, power));

    }
}
  
  🡮
Sum: 17.000
Diff: 3.000
Product: 70.000
Quotient: 1.429
Remainder: 3
Postfix increment(c): 1
Prefix increment(d):2
Postfix increment(c): 2
Prefix increment(d):3
Postfix decrement(c): 3
Prefix decrement(d):2
Postfix decrement(c): 2
Prefix decrement(d):1
(c): 1
(d):1
Floor division of 10.00 / 3.00 is: 3
2.00 raised to the power of 3.00 is : 8.00
  

赋值运算符(Assignment Operators)

赋值运算符(示例)首先将存储在变量a中的值与存储在变量b中的值按算数运算符计算,然后将结果赋值为存储在变量a中的新值。=运算符理解为"赋值",而不是“等于”,避免与==相等比较运算符混淆。

运算符 等价于(Equivalent) Py C C++ C#
= a = b ☑️ ☑️ ☑️ ☑️
+= a = (a+b) ☑️ ☑️ ☑️ ☑️
-= a = (a-b) ☑️ ☑️ ☑️ ☑️
*= a = (a*b) ☑️ ☑️ ☑️ ☑️
/= a = (a/b) ☑️ ☑️ ☑️ ☑️
%= a = (a%b) ☑️ ☑️ ☑️ ☑️
//= a = (a//b) ☑️
**= a = (a**b) ☑️
  a = 5
b = 3

a += b
print(f"Variable a = {a}, b = {b}")

a -= b
print(f"Variable a = {a}, b = {b}")

a *= b
print(f"Variable a = {a}, b = {b}")

a /= b
print(f"Variable a = {a}, b = {b}")

a %= b
print(f"Variable a = {a}, b = {b}")

a **= b
print(f"Variable a = {a}, b = {b}")

a //= b
print(f"Variable a = {a}, b = {b}")
  
  🡮
Variable a = 8, b = 3
Variable a = 5, b = 3
Variable a = 15, b = 3
Variable a = 5.0, b = 3
Variable a = 2.0, b = 3
Variable a = 8.0, b = 3
Variable a = 2.0, b = 3
  
  #include <stdio.h>

int main() {
	int a = 5, b = 3;

	a += b;
	printf("Variable a = %d, b = %d\n", a, b);

	a -= b;
	printf("Variable a = %d, b = %d\n", a, b);

	a *= b;
	printf("Variable a = %d, b = %d\n", a, b);

	a /= b;
	printf("Variable a = %d, b = %d\n", a, b);

	a %= b;
	printf("Variable a = %d, b = %d\n", a, b);

	return 0;
}
  
  🡮
Variable a = 8, b = 3
Variable a = 5, b = 3
Variable a = 15, b = 3
Variable a = 5, b = 3
Variable a = 2, b = 3
  

使用继承 C 语言的格式说明符进行格式化输出。因此下述代码除了引入的头文件不同外,与 C 保持一致。

  #include <iostream>

int main()
{
	int a = 5, b = 3;

	a += b;
	printf("Variable a = %d, b = %d\n", a, b);

	a -= b;
	printf("Variable a = %d, b = %d\n", a, b);

	a *= b;
	printf("Variable a = %d, b = %d\n", a, b);

	a /= b;
	printf("Variable a = %d, b = %d\n", a, b);

	a %= b;
	printf("Variable a = %d, b = %d\n", a, b);

	return 0;
}
  
  🡮
Variable a = 8, b = 3
Variable a = 5, b = 3
Variable a = 15, b = 3
Variable a = 5, b = 3
Variable a = 2, b = 3
  

使用由$标识的插值字符串格式化字符。

  using System;

class Program
{
    static void Main()
    {
        int a = 5, b = 3;

        a += b;
        Console.WriteLine($"Variable a = {a}, b = {b}", a, b);

        a -= b;
        Console.WriteLine($"Variable a = {a}, b = {b}", a, b);

        a *= b;
        Console.WriteLine($"Variable a = {a}, b = {b}", a, b);

        a /= b;
        Console.WriteLine($"Variable a = {a}, b = {b}", a, b);

        a %= b;
        Console.WriteLine($"Variable a = {a}, b = {b}", a, b);

    }
}
  
  🡮
Variable a = 8, b = 3
Variable a = 5, b = 3
Variable a = 15, b = 3
Variable a = 5, b = 3
Variable a = 2, b = 3
  
比较运算符(Comparison/Relational Operators)

比较运算中,Python 和 C# 的比较运算结果为布尔值(True 或False);C/C++ 返回值为 1(即为 True)和 0 (即为 False)。

  a = 5
b = 3
c = 3

print(f"Equality (a==b): {a == b}")
print(f"Inequality (a!=b): {a != b}")
print(f"Greater than (a>b): {a > b}" )
print(f"Less than (a<b): {a < b}")
print(f"Greater or equal (b>=c): {b >= c}")
print(f"Less or equal (b<=c): {b <= c}")
  
  🡮
Equality (a==b): False
Inequality (a!=b): True
Greater than (a>b): True
Less than (a<b): False
Greater or equal (b>=c): True
Less or equal (b<=c): True
  
  #include <stdio.h>

int main() {
	int a = 5, b = 3, c = 3;

	printf("Equality (a==b): %d\n", a == b);
	printf("Inequality (a!=b): %d\n", a != b);
	printf("Greater than (a>b): %d\n", a > b);
	printf("Less than (a<b): %d\n", a < b);
	printf("Greater or equal (b>=c): %d\n", b >= c);
	printf("Less or equal (b<=c): %d\n", b <= c);	

	return 0;
}
  
  🡮
Equality (a==b): 0
Inequality (a!=b): 1
Greater than (a>b): 1
Less than (a<b): 0
Greater or equal (b>=c): 1
Less or equal (b<=c): 1
  
  #include <iostream>
using namespace std;

int main()
{
	int a = 5, b = 3, c = 3;

	cout << "Equality (a==b): " << (a == b) << endl;
	cout << "Inequality (a!=b): " << (a != b) << endl;
	cout << "Greater than (a>b): " << (a > b) << endl;
	cout << "Less than (a<b): " << (a < b) << endl;
	cout << "Greater or equal (b>=c): " << (b >= c) << endl;
	cout << "Less or equal (b<=c): " << (b <= c) << endl;

	return 0;
}
  
  🡮
Equality (a==b): 0
Inequality (a!=b): 1
Greater than (a>b): 1
Less than (a<b): 0
Greater or equal (b>=c): 1
Less or equal (b<=c): 1
  

using namespace std;为引入标准命名空间std,从而可以直接使用std中的类和函数(其中包括常用的输入输出、数学函数和容器(Containers)等),而无需每次都加上std::的前缀。命名空间用于组织代码以避免命名冲突,而在大型项目中使用using namespace std;可能会导致命名冲突,尤其是当其他库也使用相同的命名时。因此为了避免命名冲突,应避免在头文件中使用该命令,而可以在源文件中使用;可以在特定的作用域内使用,例如函数内部,以减少潜在的命名冲突;或者只引入特定的名称,而不是整个命名空间,从而更好的控制命名空间的使用,避免潜在的命名冲突,如:

  #include <iostream>
using std::cout;
using std::endl;

int main()
{
	cout << "Hello World!" << endl;

	return 0;
}
  
  🡮
Hello World!
  
  using System;
using static System.Console;

class Program
{
    static void Main()
    {
        int a = 5, b = 3, c = 3;

        WriteLine($"Equality (a==b): {a == b}");
        WriteLine($"Inequality (a!=b): {a != b}");
        WriteLine($"Greater than (a>b): {a > b}");
        WriteLine($"Less than (a<b): {a < b}");
        WriteLine($"Greater or equal (b>=c): {b >= c}");
        WriteLine($"Less or equal (b<=c): {b <= c}");
    }
}
  
  🡮
Equality (a==b): False
Inequality (a!=b): True
Greater than (a>b): True
Less than (a<b): False
Greater or equal (b>=c): True
Less or equal (b<=c): True
  

using static System.Console;是一种使用静态导入的语法,从而可以直接访问静态类中的静态成员,而不需要每次都写出类名,例如直接调用Console类中的静态成员WriteLine,而无需每次写成Console.WriteLine,从而使得代码更加简洁和易读。但是,如果在同一文件中使用多个命名空间的静态成员,可能会导致命名冲突,而最好使用完整的类名;且虽然静态导入可以减少冗余的代码,但也通常会降低代码的可读性。

逻辑运算符 (Logical Operators)

逻辑运算符常用于条件语句,通过测试两个条件来确定是否满足要求,进而确定进一步采取何种策略。

运算符 说明 Py C C++ C#
支持10;支持TrueFalse 支持10;不支持true(True)和false(False) 支持10;支持truefalse 不支持10;支持truefalse
&&(&and) 都为 True(1) 时,返回 True(1) 支持&and 支持&& 支持&&and 支持&&
||(|or) 至少一个为 True (1)时,返回 True(1) 支持|or 支持|| 支持||or 支持||
(not) 为 True (1)时返回 False(0),为 False(0)时返回 True(1) 支持not 支持! 支持!not 支持!
  yes = 1
no = 0

print("AND (no&&no): %d", no & no)
print("AND (yes&&yes): %d", yes & yes)
print("AND (yes&&no): %d", yes & no)
print("OR (no||no): %d", no | no)
print("OR (yes||yes): %d", yes | yes)
print("OR (yes||no): %d", yes | no)
print("NOT (!yes): %d", not yes)
print("NOT (!no): %d", not no)

print("-"*50)

yes = True
no = False

print("AND (no&&no): %d", no & no)
print("AND (yes&&yes): %d", yes & yes)
print("AND (yes&&no): %d", yes & no)
print("OR (no||no): %d", no | no)
print("OR (yes||yes): %d", yes | yes)
print("OR (yes||no): %d", yes | no)
print("NOT (!yes): %d", not yes)
print("NOT (!no): %d", not no)

print("-"*50)
print("AND (yes&&yes): %d", yes and yes)
print("OR (yes||no): %d", yes or no)
  
  🡮
AND (no&&no): %d 0
AND (yes&&yes): %d 1
AND (yes&&no): %d 0
OR (no||no): %d 0
OR (yes||yes): %d 1
OR (yes||no): %d 1
NOT (!yes): %d False
NOT (!no): %d True
--------------------------------------------------
AND (no&&no): %d False
AND (yes&&yes): %d True
AND (yes&&no): %d False
OR (no||no): %d False
OR (yes||yes): %d True
OR (yes||no): %d True
NOT (!yes): %d False
NOT (!no): %d True
--------------------------------------------------
AND (yes&&yes): %d True
OR (yes||no): %d True
  
  #include <stdio.h>

int main() {
	int yes = 1, no = 0;

	printf("AND (no&&no): %d\n", no && no);
	printf("AND (yes&&yes): %d\n", yes && yes);
	printf("AND (yes&&no): %d\n", yes && no);
	printf("OR (no||no): %d\n", no || no);
	printf("OR (yes||yes): %d\n", yes || yes);
	printf("OR (yes||no): %d\n", yes || no);
	printf("NOT (!yes): %d\n", !yes);
	printf("NOT (!no): %d\n", !no);

	return 0;
}
  
  🡮
AND (no&&no): 0
AND (yes&&yes): 1
AND (yes&&no): 0
OR (no||no): 0
OR (yes||yes): 1
OR (yes||no): 1
NOT (!yes): 0
NOT (!no): 1
  
  #include <iostream>

int main()
{
	int yes = 1, no = 0;

	std::cout << "AND (no&&no): " << (no && no) << std::endl;
	std::cout << "AND (yes&&yes): " << (yes && yes) << std::endl;
	std::cout << "AND (yes&&no): " << (yes && no) << std::endl;
	std::cout << "OR (no||no): " << (no || no) << std::endl;
	std::cout << "OR (yes||yes): " << (yes || yes) << std::endl;
	std::cout << "OR (yes||no): " << (yes || no) << std::endl;
	std::cout << "NOT (!yes): " << (!yes) << std::endl;
	std::cout << "NOT (!no): " << (!no) << std::endl;

	std::cout << std::string(50, '-') << std::endl;
	bool yesB = true, noB = false;

	std::cout << "AND (no&&no): " << (noB && noB) << std::endl;
	std::cout << "AND (yes&&yes): " << (yesB && yesB) << std::endl;
	std::cout << "AND (yes&&no): " << (yesB && noB) << std::endl;
	std::cout << "OR (no||no): " << (noB || noB) << std::endl;
	std::cout << "OR (yes||yes): " << (yesB || yesB) << std::endl;
	std::cout << "OR (yes||no): " << (yesB || noB) << std::endl;
	std::cout << "NOT (!yes): " << (!yesB) << std::endl;
	std::cout << "NOT (!no): " << (!noB) << std::endl;

	std::cout << std::string(50, '-') << std::endl;

	std::cout << "AND (yes&&yes): " << (yesB and yesB) << std::endl;
	std::cout << "OR (yes||no): " << (yesB or noB) << std::endl;
	std::cout << "NOT (!no): " << (not noB) << std::endl;

	return 0;
}
  
  🡮
AND (no&&no): 0
AND (yes&&yes): 1
AND (yes&&no): 0
OR (no||no): 0
OR (yes||yes): 1
OR (yes||no): 1
NOT (!yes): 0
NOT (!no): 1
--------------------------------------------------
AND (no&&no): 0
AND (yes&&yes): 1
AND (yes&&no): 0
OR (no||no): 0
OR (yes||yes): 1
OR (yes||no): 1
NOT (!yes): 0
NOT (!no): 1
--------------------------------------------------
AND (yes&&yes): 1
OR (yes||no): 1
NOT (!no): 1
  
  using System;

class Program
{
    static void Main()
    {
        bool yes = true, no = false;

        Console.WriteLine($"AND (no&&no): {no && no}");
        Console.WriteLine($"AND (yes&&yes): {yes && yes}");
        Console.WriteLine($"AND (yes&&no): {yes && no}");
        Console.WriteLine($"OR (no||no): {no || no}");
        Console.WriteLine($"OR (yes||yes): {yes || yes}");
        Console.WriteLine($"OR (yes||no): {yes || no}");
        Console.WriteLine($"NOT (!yes): {!yes}");
        Console.WriteLine($"NOT (!no):{!no}");
    }
}
  
  🡮
AND (no&&no): False
AND (yes&&yes): True
AND (yes&&no): False
OR (no||no): False
OR (yes||yes): True
OR (yes||no): True
NOT (!yes): False
NOT (!no):True
  
按位运算符(Bitwise Operators)

按位运算符常用于嵌入式系统等电子领域,多个输入输出端口(高低电平)表示的命令操作中;以及数据压缩(通过使用位掩码,将多个布尔值存储在一个整数的不同位中,以减少内存使用)、图像处理(可以快速的调整图像的亮度、对比度、或者实现颜色的混合)、加密运算(对数据进行加密和解密)、网络编程(用于处理IP地址或子网掩码等)、性能优化(按位运算比一般乘除运算快)、游戏开发(用于状态标志管理)和错误检测和纠正(数据传输中,用于生成和检测校验位,确保数据传输过程中没有发生错误)等。

Python、C++ 和 C# 同时支持整数和以0b开头标识的二进制数值的按位运算;C 只支持整数按位操作,没有类似0b的二进制表示。

符号 描述 运算规则 示例
& 按位与 两个位都为1时,结果才为1 1010 & 1100 = 1000
| 按位或 两个位都为0时,结果才为0 1010 | 0101 = 1111
^ 按位异或 两个位相同为0,相异为1 1010 ^ 0100 = 1110
~ 按位取反 0变1、1变0 ~1010 = 0101
« 左移 各二进位全部左移指定位数,高位丢弃,低位补0 0010 « 2 = 1000
» 右移 各二进位全部右移指定位数,对无符号数,高位补0;有符号数,各编译器处理方法不一,可补符号位(算数右移)、可补0(逻辑右移) 1000 » 2 = 0010

典型用法:

& 按位与典型用法

  • 取一个位串信息的某几位,例如x& 0xF0(P2 & 0xF0),如果x为10010101,即10010101&11110000,结果为1001000,可见高4为被提取出来保持数值不变,低4为全部为0;
  • 让某变量保留某几位,例如x&= 0xF0,&=为复合赋值运算符_逻辑与赋值,相当于x=x & 0xF0。0xF0为设计好的一个常数,该常数种只有需要的为是1,不需要的位则为0。

\| 按位或典型用法:

将一个位串信息的某几位置1。例如x|=0xF0(P2 |=0xF0),|=为复合赋值运算符_逻辑或赋值,相当于x=x|0xF0。如果x为10010101,即10010101|11110000,结果为11110101,高4位全部变成1,低4位保持不变。

^ 按位异或典型用法

求一个位串信息某几位信息的反。例如x^=0xF0,^=为复合赋值运算符_逻辑异或赋值,相当于x=x ^ 0xF0,如果x=10010101,即10010101|11110000,结果为01100101,高4位求得其反,低4位保持不变。

~ 按位取反典型用法

相关于一个已知常数,将一个位串信息的某几位置0。例如x=x & ~0xF0,如果x为10010101,即10010101 & ~11110000=10010101 & 00001111=00000101,可见高4位置0,低4位保持不变。

<< 左移与 >> 右移配合位运算能够实现多种位串运算有关的复杂计算

  • ~(~0«n),实现最低n位为1,其余位为0的位串信息,注意优先级计算;
  • (x»(1+p-n)) & ~(~0«n),截取变量x自p位开始,右边n位的信息;
  • new|= ((old»row)&1)«(15-k),截取old变量第row位,并将该位信息装配到变量new的第15-k位;
  • s&= ~(1«j),将变量s的第j位置置0,其余位保持不变;
  • for(j=0;((1«j)&s)==0;j++),设s不等于全0,代码寻找最右边为1的位的序号j。

Python 中使用补码[附1]表示法来处理整数,因此按位取反运算符~会对整数的每一位进行翻转,结果为-n - 1,其中n是原数。如对1010(10)取反,其结果为-10 - 1 = -11,对应二进制数为0b-1011(Pyton 中负数也可以用 0b表示)。因此对于用补码表示法处理整数的 Python,按位取反后的结果是负数的补码,而不是简单的按位取反后的正数。

  a = 10
b = 5
c = 12
d = 4
e = 2
f = 8

print(f"DEC a={a};BIN a={bin(a)}")
print(f"DEC b={b};BIN b={bin(b)}")
print(f"DEC c={c};BIN c={bin(c)}")
print(f"DEC d={d};BIN d={bin(d)}")
print(f"DEC e={e};BIN e={bin(e)}")
print(f"DEC f={f};BIN f={bin(f)}")

and_result = a & c
print(f"a & c={bin(and_result)}")

or_result = a | b
print(f"a | b={bin(or_result)}")

xor_result = a ^ d
print(f"a ^ d={bin(xor_result)}")

not_result = ~a
print(f"~a={bin(not_result)}")

leftShift_result = e << 2
print(f"e << 2={bin(leftShift_result)}")

rightShift_result = f >> 2
print(f"f >> 2={bin(rightShift_result)}")
  
  🡮
DEC a=10;BIN a=0b1010
DEC b=5;BIN b=0b101
DEC c=12;BIN c=0b1100
DEC d=4;BIN d=0b100
DEC e=2;BIN e=0b10
DEC f=8;BIN f=0b1000
a & c=0b1000
a | b=0b1111
a ^ d=0b1110
~a=-0b1011
e << 2=0b1000
f >> 2=0b10
  

直接用0b前缀表示的二进制数。定义了一个函数print_binary()辅助转化十进制数显示为二进制数为指定的位数(bits)。

  def print_binary(n, bits):
    return (
        bin(n).replace("0b", "").zfill(bits)
    )  # Converts to binary and pads with zeros


a = 0b1010
b = 0b0101
c = 0b1100
d = 0b0100
e = 0b0010
f = 0b1000

bits = 4

print(f"DEC a={a};BIN a={print_binary(a,bits)}")
print(f"DEC b={b};BIN b={print_binary(b,bits)}")
print(f"DEC c={c};BIN c={print_binary(c,bits)}")
print(f"DEC d={d};BIN d={print_binary(d,bits)}")
print(f"DEC e={e};BIN e={print_binary(e,bits)}")
print(f"DEC f={f};BIN f={print_binary(f,bits)}")

and_result = a & c
print(f"a & c={print_binary(and_result,bits)}")

or_result = a | b
print(f"a | b={print_binary(or_result,bits)}")

xor_result = a ^ d
print(f"a ^ d={print_binary(xor_result,bits)}")

not_result = ~a
print(f"~a={print_binary(not_result,bits)}")

leftShift_result = e << 2
print(f"e << 2={print_binary(leftShift_result,bits)}")

rightShift_result = f >> 2
print(f"f >> 2={print_binary(rightShift_result,bits)}")
  
  🡮
DEC a=10;BIN a=1010
DEC b=5;BIN b=0101
DEC c=12;BIN c=1100
DEC d=4;BIN d=0100
DEC e=2;BIN e=0010
DEC f=8;BIN f=1000
a & c=1000
a | b=1111
a ^ d=1110
~a=-1011
e << 2=1000
f >> 2=0010
  

定义printBinary()函数辅助转化十进制整数值显示为二进制表示。

  #include <stdio.h>

void printBinary(unsigned int number, int bits) {
	for (int i = bits - 1; i >= 0; i--) {
		// Print each bit
		printf("%d", (number >> i) & 1);

		// Add a space every 4 bits for better readability
		if (i % 4 == 0 && i != 0) {
			printf(" ");
		}
	}
	printf("\n");
}

int main() {
	int a = 10, b = 5, c = 12, d = 4, e = 2, f = 8;
	int bits = 4;

	printf("DEC a=%d;BIN a=", a);
	printBinary(a, bits);

	printf("DEC b=%d;BIN b=", b);
	printBinary(b, bits);

	printf("DEC c=%d;BIN c=", c);
	printBinary(c, bits);

	printf("DEC d=%d;BIN d=", d);
	printBinary(d, bits);

	printf("DEC e=%d;BIN e=", e);
	printBinary(e, bits);

	printf("DEC f=%d;BIN f=", f);
	printBinary(f, bits);

	int and_result = a & c;
	printf("a & c=0b");
	printBinary(and_result, bits);

	int or_result = a | b;
	printf("a | b=0b");
	printBinary(or_result, bits);

	int xor_result = a ^ d;
	printf("a ^ d=0b");
	printBinary(xor_result, bits);

	int not_result = ~a;
	printf("~a =0b");
	printBinary(not_result, bits);

	int leftShift_result = e << 2;
	printf("e << 2 =0b");
	printBinary(leftShift_result, bits);

	int rightShift_result = f >> 2;
	printf("f >> 2 =0b");
	printBinary(rightShift_result, bits);

	return 0;
}
  
  🡮
DEC a=10;BIN a=1010
DEC b=5;BIN b=0101
DEC c=12;BIN c=1100
DEC d=4;BIN d=0100
DEC e=2;BIN e=0010
DEC f=8;BIN f=1000
a & c=0b1000
a | b=0b1111
a ^ d=0b1110
~a =0b0101
e << 2 =0b1000
f >> 2 =0b0010
  
  #include <iostream>
#include <bitset>
#include <format>

int main()
{
	int a = 10, b = 5, c = 12, d = 4, e = 2, f = 8;

	std::cout << std::format("DEC a={};BIN a=", a) << std::bitset<4>(a) << std::endl;
	std::cout << std::format("DEC b={};BIN b=", b) << std::bitset<4>(b) << std::endl;
	std::cout << std::format("DEC c={};BIN c=", c) << std::bitset<4>(c) << std::endl;
	std::cout << std::format("DEC d={};BIN d=", d) << std::bitset<4>(d) << std::endl;
	std::cout << std::format("DEC e={};BIN e=", e) << std::bitset<4>(e) << std::endl;
	std::cout << std::format("DEC f={};BIN f=", f) << std::bitset<4>(f) << std::endl;

	int and_result = a & c;
	std::cout << "a & c=0b" << std::bitset<4>(and_result) << std::endl;

	int or_result = a | b;
	std::cout << "a | b=0b" << std::bitset<4>(or_result) << std::endl;

	int xor_result = a ^ d;
	std::cout << "a ^ d=0b" << std::bitset<4>(xor_result) << std::endl;

	int not_result = ~a;
	std::cout << "~a=0b" << std::bitset<4>(not_result) << std::endl;

	int leftShift_result = e << 2;
	std::cout << "e << 2=0b" << std::bitset<4>(leftShift_result) << std::endl;

	int rightShift_result = f >> 2;
	std::cout << "f >> 2=0b" << std::bitset<4>(rightShift_result) << std::endl;

	return 0;
}
  
  🡮
DEC a=10;BIN a=1010
DEC b=5;BIN b=0101
DEC c=12;BIN c=1100
DEC d=4;BIN d=0100
DEC e=2;BIN e=0010
DEC f=8;BIN f=1000
a & c=0b1000
a | b=0b1111
a ^ d=0b1110
~a=0b0101
e << 2=0b1000
f >> 2=0b0010
  

直接用0b前缀表示的二进制数。

  #include <iostream>
#include <bitset>
#include <format>

int main()
{
	int a = 0b1010, b = 0b0101, c = 0b1100, d = 0b0100, e = 0b0010, f = 0b1000;

	std::cout << std::format("DEC a={};BIN a=", a) << std::bitset<4>(a) << std::endl;
	std::cout << std::format("DEC b={};BIN b=", b) << std::bitset<4>(b) << std::endl;
	std::cout << std::format("DEC c={};BIN c=", c) << std::bitset<4>(c) << std::endl;
	std::cout << std::format("DEC d={};BIN d=", d) << std::bitset<4>(d) << std::endl;
	std::cout << std::format("DEC e={};BIN e=", e) << std::bitset<4>(e) << std::endl;
	std::cout << std::format("DEC f={};BIN f=", f) << std::bitset<4>(f) << std::endl;

	int and_result = a & c;
	std::cout << "a & c=0b" << std::bitset<4>(and_result) << std::endl;

	int or_result = a | b;
	std::cout << "a | b=0b" << std::bitset<4>(or_result) << std::endl;

	int xor_result = a ^ d;
	std::cout << "a ^ d=0b" << std::bitset<4>(xor_result) << std::endl;

	int not_result = ~a;
	std::cout << "~a=0b" << std::bitset<4>(not_result) << std::endl;

	int leftShift_result = e << 2;
	std::cout << "e << 2=0b" << std::bitset<4>(leftShift_result) << std::endl;

	int rightShift_result = f >> 2;
	std::cout << "f >> 2=0b" << std::bitset<4>(rightShift_result) << std::endl;

	return 0;
}
  
  🡮
DEC a=10;BIN a=1010
DEC b=5;BIN b=0101
DEC c=12;BIN c=1100
DEC d=4;BIN d=0100
DEC e=2;BIN e=0010
DEC f=8;BIN f=1000
a & c=0b1000
a | b=0b1111
a ^ d=0b1110
~a=0b0101
e << 2=0b1000
f >> 2=0b0010
  

std::bitset为 C++ 标准库中的一个模板类,用于管理和操作固定大小的二进制位序列。在创建std::bitset时,必须指定位的大小,如std::bitset<8> b中的<8>为8位。并可以将std::bitset转换为字符串或整数类型。常用的成员函数包括:

  • set():设置所有位为1,或设置特定位置的位为1。
  • reset():将所有位设置为0,或者重置特定位置的位。
  • flip():翻转所有位,或者翻转特定位置的位。
  • test():检查特定位置的位是否为1。
  • count():返回当前值为1的位的数量。
  • size():返回位集的大小。
  • to_string():将std::bitset转换为字符串表示。
  • to_ulong():将std::bitset转换为无符号长整型。
  #include <iostream>
#include <bitset>
#include <string>

int main() {
    // 创建一个包含 8 位的 bitset
    std::bitset<8> b; 

    // 设置特定位
    b.set(3);  // 设置第 3 位
    b.set(5);  // 设置第 5 位
    std::cout << "After setting bits: " << b << std::endl; 

    // 清除特定位
    b.reset(3); // 清除第 3 位
    std::cout << "After resetting bit 3: " << b << std::endl; 

    // 翻转所有位
    b.flip(); // 翻转位
    std::cout << "After flipping: " << b << std::endl; 

    // 检查特定位
    std::cout << "Bit at position 5: " << b.test(5) << std::endl; 

    // 统计为 1 的位数
    std::cout << "Number of bits set to 1: " << b.count() << std::endl; 

    // 转换为字符串
    std::string str = b.to_string();
    std::cout << "String representation: " << str << std::endl; 

    // 转换为无符号长整型
    unsigned long value = b.to_ulong();
    std::cout << "Unsigned long representation: " << value << std::endl;

    return 0;
}
  
  🡮
After setting bits: 00101000
After resetting bit 3: 00100000
After flipping: 11011111
Bit at position 5: 0
Number of bits set to 1: 7
String representation: 11011111
Unsigned long representation: 223
  

定义printBinary()方法辅助转化十进制整数值显示为二进制表示。

  using System;

class Program
{
    static void printBinary(int number, int bits)
    {
        // Convert the number to binary and pad with leading zeros
        string binary = Convert.ToString(number, 2).PadLeft(bits, '0');

        // Format the output with spaces every 4 bits for readability
        for (int i = 0; i < binary.Length; i++)
        {
            Console.Write(binary[i]);
            if ((i + 1) % 4 == 0 && i != binary.Length - 1)
            {
                Console.Write(" ");
            }
        }
        Console.WriteLine();
    }

    static void Main()
    {
        int a = 10, b = 5, c = 12, d = 4, e = 2, f = 8;
        int bits = 4;

        Console.Write($"DEC a={a};BIN a=");
        printBinary(a, bits);

        Console.Write($"DEC b={b};BIN b=");
        printBinary(b, bits);

        Console.Write($"DEC c={c};BIN c=");
        printBinary(c, bits);

        Console.Write($"DEC d={d};BIN d=");
        printBinary(d, bits);

        Console.Write($"DEC e={e};BIN e=");
        printBinary(e, bits);

        Console.Write($"DEC f={f};BIN f=");
        printBinary(f, bits);

        int and_result = a & c;
        Console.Write("a & c=0b");
        printBinary(and_result, bits);

        int or_result = a | b;
        Console.Write("a | b=0b");
        printBinary(or_result, bits);

        int xor_result = a ^ d;
        Console.Write("a ^ d=0b");
        printBinary(xor_result, bits);

        int not_result = ~a;
        Console.Write("~a =0b");
        printBinary(not_result, bits);

        int leftShift_result = e << 2;
        Console.Write("e << 2 =0b");
        printBinary(leftShift_result, bits);

        int rightShift_result = f >> 2;
        Console.Write("f >> 2 =0b");
        printBinary(rightShift_result, bits);
    }
}
  
  🡮
DEC a=10;BIN a=1010
DEC b=5;BIN b=0101
DEC c=12;BIN c=1100
DEC d=4;BIN d=0100
DEC e=2;BIN e=0010
DEC f=8;BIN f=1000
a & c=0b1000
a | b=0b1111
a ^ d=0b1110
~a =0b1111 1111 1111 1111 1111 1111 1111 0101
e << 2 =0b1000
f >> 2 =0b0010
  

直接用0b前缀表示的二进制数。

  using System;

class Program
{
    static void Main()
    {
        int a = 0b1010, b = 0b0101, c = 0b1100, d = 0b0100, e = 0b0010, f = 0b1000;
        Console.WriteLine($"DEC a={a};BIN a={Convert.ToString(a, 2)}");
        Console.WriteLine($"DEC b={b};BIN b={Convert.ToString(b, 2)}");
        Console.WriteLine($"DEC c={c};BIN c={Convert.ToString(c, 2)}");
        Console.WriteLine($"DEC d={d};BIN d={Convert.ToString(d, 2)}");
        Console.WriteLine($"DEC e={e};BIN e={Convert.ToString(e, 2)}");
        Console.WriteLine($"DEC f={f};BIN f={Convert.ToString(f, 2)}");

        int and_result = a & c;
        Console.WriteLine($"a & c=0b{Convert.ToString(and_result, 2)}");

        int or_result = a | b;
        Console.WriteLine($"a | b=0b{Convert.ToString(or_result, 2)}");

        int xor_result = a ^ d;
        Console.WriteLine($"a ^ d=0b{Convert.ToString(xor_result, 2)}");

        int not_result = ~a;
        Console.WriteLine($"~a=0b{Convert.ToString(not_result, 2)}");

        int leftShift_result = e << 2;
        Console.WriteLine($"e << 2=0b{Convert.ToString(leftShift_result, 2)}");

        int rightShift_result = f >> 2;
        Console.WriteLine($"f >> 2=0b{Convert.ToString(rightShift_result, 2)}");
    }
}
  
  🡮
DEC a=10;BIN a=1010
DEC b=5;BIN b=101
DEC c=12;BIN c=1100
DEC d=4;BIN d=100
DEC e=2;BIN e=10
DEC f=8;BIN f=1000
a & c=0b1000
a | b=0b1111
a ^ d=0b1110
~a=0b11111111111111111111111111110101
e << 2=0b1000
f >> 2=0b10
  

成员运算符 (Membership Operators)

C 系列语言并没有类似 Python 中的成员运算符,一般通过迭代循环,或提供的方法实现。

运算 说明 Py C C++ C#
a in b 如果a在序列b中,则为True ☑️
通过迭代循环比较值的方法实现

可用std::find等方法替代

可用Array.Exists()List.Contains()string.Contains()等方法替代
a not in b 如果a不在序列b中,则为True ☑️
  numbers = [1, 2, 3, 4, 5, 6]
searchNum = 3

if searchNum in numbers:
    print(f"{searchNum} is in the array.")
else:
    print(f"{searchNum} is not in the array.")

searchNum = 9

if searchNum not in numbers:
    print(f"{searchNum} is not in the array.")
else:
    print(f"{searchNum} is in the array.")

fruits = ["apple", "banana", "cherry"]
searchFruit = "banana"

if searchFruit in fruits:
    print(f"{searchFruit} is in the list.")
else:
    print(f"{searchFruit} is not in the list.")

sentence = "Hello world!"
searchChar = "o"

if searchChar in sentence:
    print(f"The character '{searchChar}' is in the sentence.")
else:
    print(f"The character '{searchChar}' is not in the sentence.")
  
  🡮
3 is in the array.
9 is not in the array.
banana is in the list.
The character 'o' is in the sentence.
  

C 中没有像 Python 中的innot in运算符,通常使用数组(array)或结构体(structures),通过迭代循环用==运算符检查一个值是否存在于给定的数组中,如定义的contains()函数。

  #include <stdio.h>

int contains(int arr[], int size, int value) {
	for (int i = 0; i < size; i++) {
		if (arr[i] == value) {
			return 1; // value found
		}
	}
	return 0; // value not found
}

int main() {
	int numbers[] = { 1,2,3,4,5 };
	int value2find = 3;

	if (contains(numbers, sizeof(numbers) / sizeof(numbers[0]), value2find)) {
		printf("%d is in the array.\n", value2find);
	}
	else {
		printf("%d is not in the array.\n", value2find);
	}

	return 0;
}
  
  🡮
3 is in the array.
  

C++ 中没有像 Python 中的innot in运算符,但提供了std::vectorstd::set这样的容器(cntainer),可以使用std::find方法来检查成员关系。

  #include <iostream>
#include <vector>
#include <algorithm> // For std::find

int main() {
    std::vector<int> numbers = { 1,2,3,4,5 };
    int value2find = 3;

    //Using std::find jto check membership
    if (std::find(numbers.begin(), numbers.end(), value2find) != numbers.end()) {
        std::cout << value2find << " is in the vector." << numbers.end()<<std::endl;
    }
    else {
        std::cout << value2find << " is not in the vector." << std::endl;
    }

    return 0;
}
  
  🡮
3 is in the vector.
  

C# 中没有像 Python 中的innot in运算符,但是对于数组(Array)可以用Exists()方法;对于列表(List)和字符串(string)可以用Contains()方法。

  using System;

class Program
{
    static void Main()
    {
        // Example with an array
        int[] numbers = { 1, 2, 3, 4, 5, 6 };
        int searchNum = 3;

        if (Array.Exists(numbers, element => element == searchNum))
        {
            Console.WriteLine($"{searchNum} is in the array.");
        }
        else
        {
            Console.WriteLine($"{searchNum} is not in the array.");
        }

        // Example with a List
        List<string> fruits=new List<string>{"apple","banana","cherry" };
        string searchFruit = "banana";

        if (fruits.Contains(searchFruit))
        {
            Console.WriteLine($"{searchFruit} is in the list.");
        }
        else
        {
            Console.WriteLine($"{searchFruit} is not in the list.");
        }

        string sentence = "Hello world!";
        char searchChar = 'o';

        if (sentence.Contains(searchChar)) {
            Console.WriteLine($"The character '{searchChar}' is in the sentence.");
        } 
        else
        {
            Console.WriteLine($"The character '{searchChar}' is not in the sentence.");
        }

    }
}
  
  🡮
3 is in the array.
banana is in the list.
The character 'o' is in the sentence.
  

同一运算符 (Identity Operators)

C 系列语言并没有 Python 支持的同一运算符isis not,但是对于 C/C++ 可以通过==!=运算符比较两个变量值是否相等,并比较其指针(pointer)所指向的存储地址是否为同一地址;C# 可以直接使用==!=。虽然 C# 同样支持指针,但其被认为是不安全的,通常仅限于关键性能优化和较低等级的内存操作等场景中使用。

运算 说明 Py C C++ C#
a is b 如果变量 a 和 b 指向同一个 Python 对象,则结果为 True ☑️
a is not b 如果变量 a 和 b 指向不同的 Python 对象,则结果为 True ☑️
  a = 5,
b = 5
c = a

if a is c:
	print("a is equal to c.")
else:
	print("a is not equal to c.")

if a is not c:
	print("a is not equal to c.")
else:
	print("a is equal to c.")

if a is b:
	print("a is equal to b.")
else:
	print("a is not equal to b.")

print(f"a id={id(a)}\nb id={id(b)}\nc id={id(c)}")

if id(a)==id(b):
	print("a and b point to the same address.")
else:
	print("a and b point to different addresses.")
  
  🡮
a is equal to c.
a is equal to c.
a is not equal to b.
a id=2702593099088
b id=140736187992632
c id=2702593099088
a and b point to different addresses.
  
  #include <stdio.h>

int main() {
	int a = 5, b = 5;
	int c = a;
	int* ptr1 = &a; // & 为取址运算符,用于获取变量的内存地址
	int* ptr2 = &b;
	int* ptr3 = &c;

	// Comparing values
	if (a == c) {
		printf("a is equal to c.\n");
	}
	else {
		printf("a is not equal to c.\n");
	}

	//Comparing pointers
	if (ptr1 == ptr2) {
		printf("ptr1 and ptr2 point to the same address.\n");
	}
	else {
		printf("ptr1 and ptr2 point to different addresses.\n");
	}

	if (ptr1 == ptr3) {
		printf("ptr1 and ptr3 point to the same address.\n");
	}
	else {
		printf("ptr1 and ptr3 point to different addresses.\n");
	}

	return 0;
}
  
  🡮
a is equal to c.
ptr1 and ptr2 point to different address.
ptr1 and ptr3 point to different address.
  
  #include <iostream>

int main() {
	int a = 5, b = 5;
	int c = a;
	int* ptr1 = &a; // & 为取址运算符,用于获取变量的内存地址
	int* ptr2 = &b;
	int* ptr3 = &c;

	// Comparing values
	if (a == c) {
		std::cout << "a is equal to c." << std::endl;
	}
	else {
		std::cout << "a is not equal to c" << std::endl;
	}

	//Comparing pointers
	if (ptr1 == ptr2) {
		std::cout << "ptr1 and ptr2 point to the same address." << std::endl;
	}
	else {
		std::cout << "ptr1 and ptr2 point to different addresses." << std::endl;
	}

	if (ptr1 == ptr3) {
		std::cout << "ptr1 and ptr3 point to the same address." << std::endl;
	}
	else {
		std::cout << "ptr1 and ptr3 point to different addresses." << std::endl;
	}

	return 0;
}
  
  🡮
a is equal to c.
ptr1 and ptr2 point to different address.
ptr1 and ptr3 point to different address.
  
  using System;

class Program
{
    static void Main()
    {
        object obj1 = new object();
        object obj2 = obj1; // obj2 reference the same object as obj1
        object obj3 = new object(); // a different object

        // Reference equality
        Console.WriteLine($"obj1==obj2: {obj1 == obj2}");
        Console.WriteLine($"obj1==obj3:{obj1 == obj3}");

        // Example with value types
        int a = 5, b = 5;
        Console.WriteLine($"a==b: {a == b}");
    }
}
  
  🡮
obj1==obj2: True
obj1==obj3:False
a==b: True
  

运算符优先级 (Precedence and Associativity Rule of Operators)

包括多个运算符时,优先顺序可以从各个语言对应的表格中查询。4 门语言的运算符优先级顺序基本保持一致,因为 Python 和 C 系列语言的运算符有所差异,相较 C 系列语言之间的细微差异,Python 与 C 系列之间的差异稍大一些。

当运算符具有相同的优先级时(处于表中的同一行),其“结和性”决定了表达式如何分组。例如,-减法是左关联的,将从左到右分组(L2R),因此9-3-1可分组为(9-3)-1;而有些运算符是右关联的,例如a+=1,是将右侧的值与左侧变量的值相加并赋值给左侧的变量(R2L)。L2R 表示 Left to right(从左到右);R2L 表示 Right to left(从右到左)。

运算符(Operator) 说明(Description) 结合性(Associativity)
()
**
圆括号(Parentheses)
幂(Exponential/Power)
L2R
R2L
+x-x~x
*///%
一元加(Unary Addition),一元减(Unary Subtraction), 按位取反(Bitwise NOT)
乘(Multiplication),除(Division), 向下取整除(Floor Division),取模运算(Modulus)
L2R
L2R
+- 算数加(Arithmetic addition),算数减(Arithmetic subtraction) L2R
<<>> 按位左移(Bitwise shift left), 按位右移(Bitwise shift right) L2R
& 按位与(Bitwise AND) L2R
^ 按位或(Bitwise OR) L2R
|
==!=>>=<<=
按位异或(Bitwise XOR)
比较运算符(Relational operators)
L2R
L2R
=+=-=*=/=//=**=%=
innot inisis not
赋值运算符(Assignment and Augmented assignment operators))
成员,同一运算符(Membership, Identity operators)
R2L
L2R
Not
And
逻辑非(Logical NOT)
逻辑与(Logical AND)
L2R
L2R
or 逻辑或(Logical OR) L2R
运算符(Operator) 结合性(Associativity)
() Function call []Array index ->Struct pointer . Struct member L2R
!Not ~ Bitwise NOT ++ Increment --Decrement +Positive sign sizeof -Negative sign * Pointer & Addressof R2L
*Multiply /Divide %Modulus L2R
+Add -Subtract L2R
<<Shift left >> Shift right L2R
< Less than <=Less than or equal to > Greater than >= Greater than or equal to L2R
==Equality !=Inequality L2R
& Bitwise AND L2R
^Bitwise XOR L2R
|Bitwise OR L2R
&& AND L2R
|| OR L2R
?:Conditional R2L
= += -= *= /= %= &= ^= |= <<= >>=Assignment operators R2L
,Comma L2R
运算符(Operator) 结合性(Associativity)
()Function call []Array index ->Class pointer .Class member L2R
!Logical NOT *Pointer --Decrement ++ Increment + Positive sign -Negative sign Sizeof & Address of R2L
* Multiply /Divide % Modulus L2R
+ Add - Subtract L2R
<= Less or equal < Less than >= Greater or equal > Greater than L2R
== Equality != Inequality L2R
&& Logical AND L2R
|| Logical OR L2R
?: Ternary R2L
+= -= *= /= %= Assignments R2L
, Comma L2R
类别(Category) 运算符(Operator) 结合性(Associativity)
Postfix () [] ++ -- L2R
Unary
Sign
Prefix
!
+ -
++ --
R2L
Multiplicative * / % L2R
Additive + - L2R
Comparative < <= > >= L2R
Equivalence == != L2R
Conditional && L2R
Conditional || L2R
Conditional ?: R2L
Assignment = += -= *= /= %= R2L
Comma , L2R