Is there a C# function that formats a 64bit “Unsigned” value to its equivalent binary value?

妖精的绣舞 提交于 2019-11-30 01:19:17

问题


To format/display a number to its equivalent binary form (in C#), I have always simply called:

Convert.ToString(myNumber, 2);

Today, I just realized that the .ToString() overload that I have been calling does not support values that are greater than 9223372036854775807. Note the .ToString() overload's signature is: .ToString(long, int). Where "long" is a 64bit signed value which max's out at 9223372036854775807.

To put it another way, using C#, when I run this:

Convert.ToString(9223372036854775808,2);

It's no surprise (due to the signature) that I receive this exception message:

The best overloaded method match for 'System.Convert.ToString(object, System.IFormatProvider)' has some invalid arguments - Argument 2: cannot convert from 'int' to 'System.IFormatProvider'

My question: Is there a .NET function that allows us to convert values greater than 9223372036854775807 to their equivalent binary format?


回答1:


You can call it unsigned or signed, but its the same if you look at it bitwise!

So if you do this:

Convert.ToString((long)myNumber,2);

you would get the same bits as you would if there were ulong implementation of Convert.ToString(), and thats why there is none... ;)

Therefore, ((long)-1) and ((ulong)-1) looks the same in memory.




回答2:


Unfortunately there's no direct .NET equivalent like Convert.ToString(ulong, int). You'll have to make your own, like the following:

public static string ConvertToBinary(ulong value){
  if(value==0)return "0";
  System.Text.StringBuilder b=new System.Text.StringBuilder();
  while(value!=0){
    b.Insert(0,((value&1)==1) ? '1' : '0');
    value>>=1;
  }
  return b.ToString();
}



回答3:


public static string UInt64ToBinary(UInt64 input)
{
    UInt32 low = (UInt32) (input & 0xFFFFFFFF);
    UInt32 high = (UInt32) (input & 0xFFFFFFFF00000000) >> 32;
    return $"{Convert.ToString(high, 2)}{Convert.ToString(low, 2)}";
}


来源:https://stackoverflow.com/questions/6985965/is-there-a-c-sharp-function-that-formats-a-64bit-unsigned-value-to-its-equival

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!