Include int by byte [4] in .NET.

I was wondering if anyone knows of an efficient way to convert an integer to byte [4]? I am trying to write an int in a MemoryStream, and this thing wants me to give it bytes

+4
source share
5 answers

You can use BitConverter.GetBytes if you want to convert a primitive type to its byte representation. Just remember to make sure that the continent is correct for your scenario.

+14
source

Use BinaryWriter (built using your memory stream); It has a write method that accepts Int32.

 BinaryWriter bw = new BinaryWriter(someStream); bw.Write(intValue); bw.Write((Int32)1); // ... 
+7
source
  • BinaryWriter will be the easiest solution to write to a stream
  • BitConverter.GetBytes most suitable if you really need an array
  • My own versions in MiscUtil ( EndianBitConverter and EndianBinaryWriter ) give you more control over the content, and also allow you to directly convert to an existing array.
+6
source

You can also make your own bias! Although I would use inline methods, I would choose this for fun.

 byte[] getBytesFromInt(int i){ return new byte[]{ (byte)i, (byte)(i >> 8), (byte)(i >> 16), (byte)(i >> 24) }; } 

Of course you need to worry about endian.

+3
source

All Articles