使用 C# 中的位运算符将给定的数字乘以 2
可以使用位运算符将数字乘以 2。这是通过使用左移运算符并将位向左移动 1 位来完成的。这将使之前的数字翻倍。
下面提供了一个使用位运算符演示将数字乘以 2 的程序。
示例
using System;
namespace BitwiseDemo {
class Example {
static void Main(string[] args) {
int num = 25, result;
result = num << 1;
Console.WriteLine("The original number is: {0}", num);
Console.WriteLine("The number multiplied by two is: {0}", result);
}
}
}输出
上述程序的输出如下。
The original number is: 25 The number multiplied by two is: 50
现在,让我们了解一下上述程序。
首先,定义数字。之后,使用左移运算符,并将 num 中的位向左移动 1 位。这将使之前的数字翻倍,存储在 result 中。之后,显示 num 和 result 的值。此代码段如下所示 -
int num = 25, result;
result = num << 1;
Console.WriteLine("The original number is: {0}", num);
Console.WriteLine("The number multiplied by two is: {0}", result);
广告
数据结构
网络
RDBMS
操作系统
Java
iPhone 操作系统
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP