Home > Software design >  Concat two byte arrays and get a byte array back
Concat two byte arrays and get a byte array back

Time:03-10

I want to convert a string into a UTF8 byte array with a BOM, but this code results in an array of objects instead of bytes:

$input = "hello world"

$encoding = [system.Text.Encoding]::UTF8
$bytes = $encoding.GetBytes($input)
$bytesWithBom = $encoding.GetPreamble()   $bytes

$encoding.GetPreamble().GetType()
$bytes.GetType()
$bytesWithBom.GetType()

Outputs:

IsPublic IsSerial Name                                     BaseType                                                                                    
-------- -------- ----                                     --------                                                                                    
True     True     Byte[]                                   System.Array                                                                                
True     True     Byte[]                                   System.Array                                                                                
True     True     Object[]                                 System.Array  

So , given two byte arrays, returns an object array. How do you concatenate and get a byte array?

CodePudding user response:

Either convert the resulting [Object[]] to [byte[]]:

$bytesWithBom = @($encoding.GetPreamble()   $bytes) -as [byte[]]

Or manually create the target array up front and copy both input arrays to it:

$preamble = $encoding.GetPreamble()
$bytesWithBom = [byte[]]::new($bytes.Length   $preamble.Length)
$preamble.CopyTo($bytesWithBom, 0)
$bytes.CopyTo($bytesWithBom, $preamble.Length)
  • Related