C
C#3y ago
WAASUL

Convert int[] to byte[]?

Could anyone help me convert an array of integers to an array of bytes?
12 Replies
WAASUL
WAASULOP3y ago
Would this be a good idea?
byte[] bytes = intArray.SelectMany(BitConverter.GetBytes).ToArray()
byte[] bytes = intArray.SelectMany(BitConverter.GetBytes).ToArray()
TheRanger
TheRanger3y ago
that doesnt make sense, since byte's maximum value is 255 what if an integer is 512 ? you probably want a 2d array
sibber
sibber3y ago
i assume they want to convert each int to an array of bytes
TheRanger
TheRanger3y ago
byte[][] bytes = intArray.Select(x => BitConverter.GetBytes(x)).ToArray();
byte[][] bytes = intArray.Select(x => BitConverter.GetBytes(x)).ToArray();
ero
ero3y ago
what they had originally makes perfect sense and works fine absolutely no reason to correct that unless they want a faster version
i love cat(mull-rom splines)
id allocate once and for it more efficient than linq
MODiX
MODiX3y ago
Ero#1111
REPL Result: Success
using System.Runtime.InteropServices;

int[] foo = { 1, 2, 3, 4, 5 };
byte[] bar = MemoryMarshal.AsBytes<int>(foo).ToArray();

bar
using System.Runtime.InteropServices;

int[] foo = { 1, 2, 3, 4, 5 };
byte[] bar = MemoryMarshal.AsBytes<int>(foo).ToArray();

bar
Result: byte[]
AQAAAAIAAAADAAAABAAAAAUAAAA=
AQAAAAIAAAADAAAABAAAAAUAAAA=
Compile: 565.667ms | Execution: 44.727ms | React with ❌ to remove this embed.
ero
ero3y ago
ah, right modix turns bytes into chars
MODiX
MODiX3y ago
Cyberrex#8052
REPL Result: Success
using System.Runtime.InteropServices;

int[] foo = { 1, 2, 3, 4, 5 };
byte[] bar = MemoryMarshal.AsBytes<int>(foo).ToArray();

string.Join("", bar)
using System.Runtime.InteropServices;

int[] foo = { 1, 2, 3, 4, 5 };
byte[] bar = MemoryMarshal.AsBytes<int>(foo).ToArray();

string.Join("", bar)
Result: string
10002000300040005000
10002000300040005000
Compile: 621.330ms | Execution: 50.969ms | React with ❌ to remove this embed.
mtreit
mtreit3y ago
I think I would use MemoryMarshal.Cast for this.
Span<byte> bytes = MemoryMarshal.Cast<int, byte>(foo);
Span<byte> bytes = MemoryMarshal.Cast<int, byte>(foo);
TheRanger
TheRanger3y ago
ah that slipped my mind, did not think thats what they meant even tho i used those kinds of things in a project im working on

Did you find this page helpful?