2

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?

3
  • What does your variable $cfg hold? Commented Feb 3, 2022 at 0:35
  • $cfg[($cfg.Count-1)..0] is another alternative Commented Feb 3, 2022 at 1:16
  • 3
    It might help if you were to explain the problem that you are really trying to solve (this seems like a possible XY problem). Commented Feb 3, 2022 at 3:50

2 Answers 2

3

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.