every data on computer is 0 and 1 , even though the data represent something else , but at the smallest scale it is 0 and 1 . How do i convert any type to binary string ? or to an array of integer with each integer value is either 1 or 0 and nothing else .
1 Answer
The general problem isn't solvable in C#, because in C# you can't read directly the memory of reference types (and you can't even read the memory of a reference to see where it is "pointing" to).
What you can read is the memory rappresentation of primitive types (that is Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single) but as I've said you can't really "take a look" at reference types. You can't "see" the hidden fields of a String or of an int[] for example, and it can be complex even to read the memory of complex value types (struct).
For the primitive types I listed (excluding IntPtr and UIntPr) you can
double value = 5;
string str = string.Join(" ", BitConverter.GetBytes(value).Select(x => Convert.ToString(x, 2).PadLeft(8, '0')));
For IntPtr and UIntPtr you must first downcast them to Int32/UInt32 if your process is 32 bits or Int64/UInt64 if it is 64 bits.
As a sidenote, it isn't entirely clear for me in which order should the bits of a byte be printed. I've read that "normally", on little endian systems (your PC with Intel processor), the bit order is the same as the byte order. I'm not calculating this in the code, so (int)1 on an Intel is
00000001 00000000 00000000 00000000
So I'm printing bits in a byte in big endian order, and I'm printing bytes of value types in their memory rappresentation (on Intel normally little endian)
1 Comment
unsafe? Obviously it's unsafe but in current implementations a managed ref is not a black box. I understand that is somewhat irrelevant to the general point
new int[5]