Creating an array from a list of numerical literals
An
array of bytes can simply be created by assigning an array of numbers (technically: bytes) to a typed
variable:
[byte[]] $byte_array = 65,66,67,90
Of course, typically, such numbers come in hexadecimal form in which case they need to be prepended with 0x
:
[byte[]] $another_array = 0x41, 0x42, 0x43, 0x5A
If the array of hexadecimal number comes from a source where it is not already prefixed and manually prefixing them is too tedious, a
pipeline helps to convert the hexadecimal numbers to a byte:
[byte[]] $xyz = '41', '42', '43', '5A' | foreach-object { invoke-expression "0x$_" }
Because some of the values of the last example contain characters, these values had to be enclosed in quotes.
To make things easier, we can put such values into a string and create an array using the
-split
operator:
[byte[]] $abc = "41 42 43 5A" -split ' ' | foreach-object { invoke-expression "0x$_" }
Create an array of n elements, each initialized to 0
The following constructs create byte
arrays, each of which has 10 elements and whose values are initialized to 0
.
$array_1 = [byte[]]::new(10)
$array_2 = new-object byte[] 10
$array_3 = [System.Array]::CreateInstance([byte], 10)
Creating higher dimension arrays
The following constructs create arrays of higher dimensions:
[byte[,]] $four_by_eight = [System.Array]::CreateInstance([byte], @(4, 8))
[byte[,,,]] $b_3x4x5x6 = [byte[,,,]]::new(3,4,5,6)