Skip to content

Instantly share code, notes, and snippets.

@DForshner
Created May 30, 2014 21:47
Show Gist options
  • Select an option

  • Save DForshner/5a82a58c2a717b230f4e to your computer and use it in GitHub Desktop.

Select an option

Save DForshner/5a82a58c2a717b230f4e to your computer and use it in GitHub Desktop.
Some different ways to get the bit representation of a 32 bit int.
public static class Program
{
public static void Main()
{
int value = 576;
byte[] bytes = new byte[4];
bytes[0] = (byte)(value >> 24);
bytes[1] = (byte)(value >> 16);
bytes[2] = (byte)(value >> 8);
bytes[3] = (byte)value;
DisplayBits(value, bytes);
byte[] bytes2 = new byte[4];
for (var i = (bytes2.Count() - 1); i >= 0; i--)
{
bytes2[i] = (byte)(value >> -((i - 3) * 8));
}
DisplayBits(value, bytes2);
byte[] bytes3 = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes3);
DisplayBits(value, bytes3);
Console.WriteLine("Press [Enter Key] to exit.");
Console.ReadLine();
}
private static void DisplayBits(int value, byte[] bytes3)
{
Console.WriteLine("{0} => {1} {2} {3} {4}", value,
Convert.ToString(bytes3[0], 2),
Convert.ToString(bytes3[1], 2),
Convert.ToString(bytes3[2], 2),
Convert.ToString(bytes3[3], 2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment