c# hex to bit conversion
I'm trying to convert the hexadecimal representation of a 64-bit number (eg, the string "FFFFFFFFF"
) to binary representation ( "11111..."
).
I've tried
string result = Convert.ToString(Convert.ToUInt64(value, 16), 2);
but this results in a confusing compiler error:
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'
There might be a better solution, but check if this works:
public static string HexToBinary(string hexValue)
{
ulong number = UInt64.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
byte[] bytes = BitConverter.GetBytes(number);
string binaryString = string.Empty;
foreach (byte singleByte in bytes)
{
binaryString += Convert.ToString(singleByte, 2);
}
return binaryString;
}
The most convenient way would be to use Convert.ToString(Int64, Int32)
, but there is no overload for ulong. Another solution is Convert.ToString(UInt64, IFormatProvider)
and write your own IFormatProvider. By looking at the examples I found an IFormatProvider that formats numbers in binary, octal and hex string representation: http://msdn.microsoft.com/en-us/library/system.icustomformatter.aspx. The code there looks very similar to what I provided, so I thinks its not a bad solution.
What's wrong with the following code?
string hex = "FFFFFFFFFFFFFFFF";
// Returns -1
long longValue = Convert.ToInt64(hex, 16);
// Returns 1111111111111111111111111111111111111111111111111111111111111111
string binRepresentation = Convert.ToString(longValue, 2);
Pretty much what you wrote (only fixed the ulong
to long
cast), and returns what you expect.
Edit: undeleted this answer, as even if the long
representation is signed, the binary representation is actually what you expect.
最好的选择是:
public static string hex2bin(string value)
{
return Convert.ToString(Convert.ToInt32(value, 16), 2).PadLeft(value.Length * 4, '0');
}
链接地址: http://www.djcxy.com/p/15884.html
上一篇: 将C ++ dll导出到C#
下一篇: c#十六进制到位转换