如何用C#写个16进制的算法?思维是怎么样的?
发布网友
发布时间:2022-05-29 09:41
我来回答
共1个回答
热心网友
时间:2023-10-14 19:34
什么意思啊?
进制转换吗?可以用 “ 掩码 ”,参考书《C#本质论》
//英文原文: Getting a String Representation of a Binary Display
public class BinaryConverter
{
public static void Main()
{
const int size = 64;
ulong value;
char bit;
System.Console.Write ("Enter an integer: ");
// Use long.Parse() so as to support negative numbers
// Assumes unchecked assignment to ulong.
value = (ulong)long.Parse(System.Console.ReadLine());
// Set initial mask to 100....
ulong mask = 1ul << size - 1;
for (int count = 0; count < size; count++)
{
bit = ((mask & value) > 0) ? '1': '0';
System.Console.Write(bit);
// Shift mask one location over to the right
mask >>= 1;
}
System.Console.WriteLine();
}
}
//解释:Notice that within each iteration of the for loop (discussed shortly), youuse the right-shift assignment operator to create a mask corresponding to
each bit in value. By using the & bit operator to mask a particular bit, youcan determine whether the bit is set. If the mask returns a positive result,
you set the corresponding bit to 1; otherwise, it is set to 0. In this way, youcreate a string representing the binary value of an unsigned long.
//利用了 “掩码”! 很妙!