简体   繁体   English

如何更改二进制表示中的第三位?

[英]How to change third bit in binary representation?

I'm trying to write code in which code the third bit is always one. 我正在尝试编写第三位始终为1的代码。

I've done the following to detect the third bit, but i don't know how to change it to show one , it should be done without using loops, because this exercise is from first part of book for beginners and in this chapter there is information about variables and operators in c#. 我已经完成了以下检测第三位,但我不知道如何更改它以显示一个,它应该在不使用循环的情况下完成,因为这个练习来自初学者的本书的第一部分,在本章中是关于c#中的变量和运算符的信息。

int decimalNumber = int.Parse(Console.ReadLine());
string binaryConv = Convert.ToString(decimalNumber, 2);
char thirdBite = binaryConv[2];
int decimalNumber = int.Parse(Console.ReadLine()) | 4;

The 4 is the 3rd binary digit (100 base 2 = 4 base 10). 4是第3个二进制数字(100个基数2 = 4个基数10)。

The | | is a binary OR 是二进制OR

What if you just OR the number with 4 (100 in binary)? 如果你只 4个(二进制100)是多少? This will ensure that 3rd bit is always set: 这将确保始终设置第3位:

using System;

public class Program
{
    public static void Main()
    {
        Console.Write("Enter integer value: ");
        int intVal = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("You entered: {0} (In binary this number is: {1})", intVal, Convert.ToString(intVal, 2));
        Console.WriteLine("{0} | 4 (100 in binary) = {1} (In binary this number is: {2})", intVal, intVal | 4, Convert.ToString(intVal | 4, 2));
    }
}

Example Usage 1: 示例用法1:

Enter integer value: 2
You entered: 2 (In binary this number is: 10)
2 | 4 (100 in binary) = 6 (In binary this number is: 110)

Example Usage 2: 用法示例2:

Enter integer value: 49
You entered: 49 (In binary this number is: 110001)
49 | 4 (100 in binary) = 53 (In binary this number is: 110101)

Example Usage 3: 用法示例3:

Enter integer value: -6
You entered: -6 (In binary this number is: 11111111111111111111111111111010)
-6 | 4 (100 in binary) = -2 (In binary this number is: 11111111111111111111111111111110)

Welcome. 欢迎。 Your solution will give you the third bit. 您的解决方案将为您提供第三位。 But it does it by converting to a string, which is way more expensive then it needs to be. 但它是通过转换为字符串来实现的,这比它需要的更昂贵。

Get the value of the third bit like this: 像这样得到第三位的值:

 bool thirdBit = (decimalNumber & (1 << 2)) != 0;

Make sure the 3rd bit is set ON: 确保第3位设置为ON:

 decimalNumber = decimalNumber | (1 << 2);

Make sure the 3rd bit is set OFF: 确保第3位设置为OFF:

 decimalNumber = decimalNumber & ~(1 << 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM