Finally I could write this class to print binary representation of a basic type:
class Bits
{
static void print(byte[] b, bool newline = true)
{
for(int i = b.Length - 1; 0 <= i; i--)
{
for(int j = 8; 1 <= j; j--)
Console.Write(((byte)(b[i] << (8 - j))) >> 7);
Console.Write(" ");
}
}
public static void Show<T>(T x)
{
if(typeof(T) == typeof(float))
print(BitConverter.GetBytes(float.Parse(x.ToString())));
else if(typeof(T) == typeof(double))
print(BitConverter.GetBytes(double.Parse(x.ToString())));
else if(typeof(T) == typeof(decimal))
{
int[] Bits = decimal.GetBits(decimal.Parse(x.ToString()));
for(int i = 0; i < Bits.Length; i++)
print(BitConverter.GetBytes(Bits[i]));
}
else if(typeof(T) == typeof(sbyte))
print(BitConverter.GetBytes(sbyte.Parse(x.ToString())));
else if(typeof(T) == typeof(short))
print(BitConverter.GetBytes(short.Parse(x.ToString())));
else if(typeof(T) == typeof(int))
print(BitConverter.GetBytes(int.Parse(x.ToString())));
else if(typeof(T) == typeof(long))
print(BitConverter.GetBytes(long.Parse(x.ToString())));
else if(typeof(T) == typeof(byte))
print(BitConverter.GetBytes(byte.Parse(x.ToString())));
else if(typeof(T) == typeof(ushort))
print(BitConverter.GetBytes(ushort.Parse(x.ToString())));
else if(typeof(T) == typeof(uint))
print(BitConverter.GetBytes(uint.Parse(x.ToString())));
else if(typeof(T) == typeof(ulong))
print(BitConverter.GetBytes(ulong.Parse(x.ToString())));
else if(typeof(T) == typeof(char))
print(BitConverter.GetBytes(char.Parse(x.ToString())));
else if(typeof(T) == typeof(bool))
print(BitConverter.GetBytes(bool.Parse(x.ToString())));
Console.Write("\n\n");
}
}
How to use the class:
decimal a = 123.123m; Bits.Show(a);Output:
Quote
00000000 00000001 11100000 11110011 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000011 00000000 00000000
00000000 00000000 00000000 00000000 00000011 00000000 00000000
there are a few problems:
1) sbyte.Parse(x.ToString()) is not so interesting. converting to string and then to the original number.
2) I'm not sure about decimal type.
3) show method is a template (generic), but it's definition is not like a template function. in C++ I don't need a lot of if else statements.
I would appreciate it, if you can help me solve these problems.


Sign In
Create Account


Back to top









