Reputation: 2648
The task is how to store the bytes of an int value with the correct endianess.
Basically, this works fine when on x86 systems, and the value shall be little-endian, using the .NET function GetBytes():
[byte[]]$as_little_endian = [System.BitConverter]::GetBytes($value)
# e.g.:
$value = 0x12345678
[byte[]]$as_little_endian = [System.BitConverter]::GetBytes($value)
$as_little_endian | Format-Hex
# -> ... 78 56 34 12
For example, the result can now be appended to a file when $value
is a checksum.
However, the result depends on the system architecture and may be different on other systems. There is no way to enforce a certain endianess, to keep the script independent.
As a workaround, I do this:
$as_little_endian = [System.BitConverter]::GetBytes($value)
if( -Not [System.BitConverter]::IsLittleEndian )
{
[array]::Reverse($as_little_endian )
}
Is there a more elegant way to enforce endianess here?
Upvotes: 0
Views: 648
Reputation: 27473
It looks like getbytes() returns the right order automatically. Note that tcp always uses bigendian. It seems unlikely that you would encounter a bigendian system.
The order of bytes in the array returned by the GetBytes method depends on whether the computer architecture is little-endian or big-endian.
BitConverter.GetBytes Method (System-int64) | Microsoft Learn
Upvotes: 0