I want to reverse the order of bytes in this Array
$cfg = ($cfg | ForEach-Object ToString X2)
I have tried
$cfg = [Array]::Reverse($cfg)
But after
Write-Output $cfg
There was no generated output. How can I approach this problem?
Note: The answer below addresses reversing a given array's elements, whatever their type may be. The command in your question creates an array of strings, not bytes. If you wanted to interpret these strings as byte values, you'd have to use: [byte[]] $cfg = ($cfg | ForEach-Object ToString X2) -replace '^', '0x'
That said, given that your command implies that the elements of $cfg are numbers already,
[byte[]] $cfg = $cfg should do.
[Array]::Reverse() reverses an array in place and has no return value.
Therefore, use just [Array]::Reverse($cfg) by itself - after that, $cfg, will contain the original array elements in reverse order.
A simple example:
$a = 1, 2, 3
# Reverse the array in place.
[Array]::Reverse($a)
# Output the reversed array -> 3, 2, 1
$a
If you're trying to convert a byte array to integer in LittleEndian order or "backwards"... (based on Powershell Byte array to INT)
[bitconverter]::ToInt16 # without parentheses to get declaration
OverloadDefinitions
-------------------
static int16 ToInt16(byte[] value, int startIndex)
$bytes = [byte[]](0xde,0x07)
$startIndex = 0
[bitconverter]::ToInt16($bytes,$startIndex)
2014
2014 | % tostring x4
07de # bytes are backwards
[bitconverter]::IsLittleEndian # Windows, OSX, Linux...
True
$cfghold?$cfg[($cfg.Count-1)..0]is another alternative