Skip to content

Instantly share code, notes, and snippets.

@leppie
Forked from YuvalItzchakov/gist:9b404a63337f35b5dc7e
Last active December 15, 2015 09:18
Show Gist options
  • Save leppie/99e38f228257670b9e21 to your computer and use it in GitHub Desktop.
Save leppie/99e38f228257670b9e21 to your computer and use it in GitHub Desktop.
// why masking is a good habit
// the following fails are runtime
static byte[] ToByteArray(int i)
{
checked
{
var b = new byte[4];
b[0] = (byte)(i);
b[1] = (byte)((i >> 8));
b[2] = (byte)((i >> 16));
b[3] = (byte)((i >> 24));
return b;
}
}
// assumes little endian
static int ToInt32(byte[] b) // must be 4 bytes
{
return b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24); // could be + too
}
static byte[] ToByteArray(int i)
{
var b = new byte[4];
b[0] = (byte)(i & 0xFF); // must mask higher bits
b[1] = (byte)((i >> 8) & 0xFF);
b[2] = (byte)((i >> 16) & 0xFF);
b[3] = (byte)((i >> 24) & 0xFF);
return b;
}
// assumes little endian
static unsafe int ToInt32(byte[] b) // must be 4 bytes
{
fixed (byte* bp = b)
{
return *((int*)bp);
}
}
static unsafe byte[] ToByteArray(int i)
{
var b = new byte[4];
fixed (byte* bp = b)
{
*((int*)bp) = i;
}
return b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment