C
C#14mo ago

✅ 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
Thinker14mo 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
fæ
OP14mo 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
Thinker14mo 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.
fæ
OP14mo ago
very well that makes sense, but GetBytes does that do big or little endian?
Jimmacle
Jimmacle14mo 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
Accord14mo 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.
fæ
OP14mo ago
yes i eventually settled on this thank you
Want results from more Discord servers?
Add your server