Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast int to byte[4] in .NET

Tags:

c#

.net

I was wondering if anyone here knows an efficient way to cast an integer to a byte[4]? I'm trying to write an int into MemoryStream, and this thing wants me to give it bytes

like image 533
galets Avatar asked Nov 27 '22 06:11

galets


2 Answers

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

like image 122
Greg Beech Avatar answered Dec 20 '22 19:12

Greg Beech


Use a BinaryWriter (constructed with your memory stream); it has a write method that takes an Int32.

BinaryWriter bw = new BinaryWriter(someStream);
bw.Write(intValue);
bw.Write((Int32)1);
// ...
like image 37
Daniel LeCheminant Avatar answered Dec 20 '22 21:12

Daniel LeCheminant