It would be nice if the .NET framework just gave functions/methods from the BitConverter class that just explicitly returned an array of bytes in the proper requested endianness.
I've done some functions like this in other code, but is there a shorter more direct way? (efficiency is key since this concept is used a TON in various crypto and password derivation contexts, including PBKDF2, Skein, HMAC, BLAKE2, AES and others)
// convert an unsigned int into an array of bytes BIG ENDIEN
// per the spec section 5.2 step 3 for PBKDF2 RFC2898
static internal byte[] IntToBytes(uint i)
{
byte[] bytes = BitConverter.GetBytes(i);
if (!BitConverter.IsLittleEndian)
{
return bytes;
}
else
{
Array.Reverse(bytes);
return bytes;
}
}
I also see that others struggle with this question, and I haven't seen a good answer yet :( How to deal with 'Endianness'