C
C#16mo ago
zzzz

✅ filling byte array with a random int

best approach?
BinaryPrimitives.WriteInt32BigEndian(bytes, Random.Shared.Next(5000000));
//vs
bytes = BitConverter.GetBytes(Random.Shared.Next(5000000));
BinaryPrimitives.WriteInt32BigEndian(bytes, Random.Shared.Next(5000000));
//vs
bytes = BitConverter.GetBytes(Random.Shared.Next(5000000));
8 Replies
Thinker
Thinker16mo ago
oh I forgot BitConverter was a thing, sorry Both should be fine I think, although BinaryPrimitives.WriteInt32BigEndian might be a bit more efficient, but that's not really something you should worry about
zzzz
zzzzOP16mo ago
However i must ask, the BinaryPrimitives class has both big endian and little endian methods what would be the difference? and compared to just GetBytes? the latter doesnt make that distinction
Thinker
Thinker16mo ago
(this is a bit low-level) An int is 4 bytes. Say if we have the number 134480385, we can write it in two ways:
00001000 00000100 00000010 00000001 // big endian
or
00000001 00000010 00000100 00001000 // little endian
00001000 00000100 00000010 00000001 // big endian
or
00000001 00000010 00000100 00001000 // little endian
Big endian puts the most significant byte first, little endian puts the least significant byte first, 00000001 being the least significant byte and 00001000 being the most significant.
zzzz
zzzzOP16mo ago
very well that makes sense, but GetBytes does that do big or little endian?
Jimmacle
Jimmacle16mo ago
i would assume it depends on the endianness of the architecture which is little endian for basically any modern system bitconverter is an older API anyway, i'd prefer BinaryPrimitives
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
zzzz
zzzzOP16mo ago
yes i eventually settled on this thank you

Did you find this page helpful?