public static void Main()
private static void Write(byte v)
Console.WriteLine((byte)v);
Console.WriteLine(ToBinaryString((byte)v, true, true));
Console.WriteLine((byte)S3TC1ReverseByte((byte)v));
Console.WriteLine(ToBinaryString((byte)S3TC1ReverseByte((byte)v), true, true));
private static byte S3TC1ReverseByte(byte blockByte)
byte blockBit1 = (byte)(blockByte & 0b0000_0011);
byte blockBit2 = (byte)(blockByte & 0b0000_1100);
byte blockBit3 = (byte)(blockByte & 0b0011_0000);
byte blockBit4 = (byte)(blockByte & 0b1100_0000);
return (byte)((blockBit1 << 6) | (blockBit2 << 2) | (blockBit3 >> 2) | (blockBit4 >> 6));
public static string ToBinaryString<T>(T input, bool usePrefix = false, bool useSeperator = false) where T : struct
if (typeof(T) == typeof(sbyte))
bin = ((sbyte)(object)input).ToBinaryString();
else if (typeof(T) == typeof(byte))
bin = ((byte)(object)input).ToBinaryString();
else if (typeof(T) == typeof(short))
bin = ((short)(object)input).ToBinaryString();
else if (typeof(T) == typeof(ushort))
bin = ((ushort)(object)input).ToBinaryString();
else if (typeof(T) == typeof(int))
bin = ((int)(object)input).ToBinaryString();
else if (typeof(T) == typeof(uint))
bin = ((uint)(object)input).ToBinaryString();
else if (typeof(T) == typeof(ulong))
bin = ((ulong)(object)input).ToBinaryString();
else if (typeof(T) == typeof(long))
bin = ((long)(object)input).ToBinaryString();
StringBuilder bincv = new StringBuilder(usePrefix ? "0b" : "");
for (int c = 0; c < bin.Length; c += 4)
for (int i = 0; i < 4; i++)
bincv.Append(bin[c + i]);
if (useSeperator && c != (bin.Length - 4))
throw new NotSupportedException("Only byte, sbyte, ushort, short, uint, int, ulong, and long are supported");
public static class ToBinaryStringExtensions
public static string ToBinaryString(this sbyte input)
return Convert.ToString(input, 2).PadLeft(sizeof(sbyte) * 8, '0');
public static string ToBinaryString(this byte input)
return Convert.ToString(input, 2).PadLeft(sizeof(byte) * 8, '0');
public static string ToBinaryString(this short input)
return Convert.ToString(input, 2).PadLeft(sizeof(short) * 8, '0');
public static string ToBinaryString(this ushort input)
return Convert.ToString(input, 2).PadLeft(sizeof(ushort) * 8, '0');
public static string ToBinaryString(this int input)
return Convert.ToString(input, 2).PadLeft(sizeof(int) * 8, '0');
public static string ToBinaryString(this uint input)
return Convert.ToString(input, 2).PadLeft(sizeof(uint) * 8, '0');
public static string ToBinaryString(this ulong input)
uint low = (uint)(input & 0xFFFFFFFF);
uint high = (uint)(input & 0xFFFFFFFF00000000) >> (sizeof(uint) * 8);
return $"{Convert.ToString(high, 2).PadLeft(sizeof(uint) * 8, '0')}{Convert.ToString(low, 2).PadLeft(sizeof(uint) * 8, '0')}";
public static string ToBinaryString(this long input)
return Convert.ToString(input, 2).PadLeft(sizeof(long) * 8, '0');