I thought .net had some kind of easy conversion method to use for converting an int into a byte array? I did a quick search and all solutions are bit masking/shifting one byte at a time, like “the good ol days”.
Is there not a ToByteArray() method somewhere?
I thought .net had some kind of easy conversion method to use for converting
Share
Update for 2020 –
BinaryPrimitivesshould now be preferred overBitConverter. It provides endian-specific APIs, and is less allocatey.although note also that you might want to check
BitConverter.IsLittleEndianto see which way around that is going to appear!Note that if you are doing this repeatedly you might want to avoid all those short-lived array allocations by writing it yourself via either shift operations (
>>/<<), or by usingunsafecode. Shift operations also have the advantage that they aren’t affected by your platform’s endianness; you always get the bytes in the order you expect them.