gpt4 book ai didi

c# - ulong 和 long 在计算值的二进制模式时有什么区别?

转载 作者:行者123 更新时间:2023-11-30 20:30:47 25 4
gpt4 key购买 nike

下面的代码允许用户输入一个整数并将其转换为二进制。输入的数字是(1) 解析成 long 类型和(2)转化为乌龙型。

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
const int size = 64;
ulong value;
char bit;

Console.WriteLine("Enter an integer");
value = (ulong)long.Parse(Console.ReadLine());

ulong mask = 1UL << size - 1;
for(int count = 0; count < size; count++)
{
bit = ((mask & value) != 0) ? '1' : '0';
Console.Write(bit);
mask >>= 1;
}

Console.ReadLine();
}
}
}

有效! input integer 42

但是如果我不把这个值转化成ulong,那就有问题了:

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
const int size = 64;
long value;
char bit;

Console.WriteLine("Enter an integer");
value = long.Parse(Console.ReadLine());

long mask = 1L << size - 1;
for(int count = 0; count < size; count++)
{
bit = ((mask & value) != 0) ? '1' : '0';
Console.Write(bit);
mask >>= 1;
}

Console.ReadLine();
}
}

enter image description here谁能告诉我为什么?

最佳答案

在二进制补码系统中,负数使用将最高有效位设置为 1 的位模式表示。因此,当您通过将 1 向左移动 63 次来制作带符号的掩码 时,您会得到一个负数:

long mask = 1L << size - 1;

这是理解接下来会发生什么的关键:右移负数会保留其符号。换句话说,如果最高有效位是 1,则 1 将被移入顶部的数字,而不是零。

您的面具将在您移动时按照以下顺序进行:

100000...000
110000...000
111000...000
111100...000
...
111111...100
111111...110
111111...111

这就是为什么条件 (mask & value) != 0 将在 1 的序列达到值中的最高设置位时变为 true 的原因,并且将保持不变一直到最后。

关于c# - ulong 和 long 在计算值的二进制模式时有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44170722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com