Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# hex to bit conversion

Tags:

c#

hex

I'm trying to convert the hexadecimal representation of a 64-bit number (e.g., 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'

like image 912
santBart Avatar asked Dec 04 '22 17:12

santBart


1 Answers

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.

like image 126
ken2k Avatar answered Dec 10 '22 09:12

ken2k