问题
I am trying to convert a Hex string to an 8-bit signed integer array in Powershell.
I am using the following function to convert a Hex string, such as A591BF86E5D7D9837EE7ACC569C4B59B, to a byte array which I then need to convert to a 8-bit signed integer array.
Function GetByteArray {
[cmdletbinding()]
param(
[parameter(Mandatory=$true)]
[String]
$HexString
)
$Bytes = [byte[]]::new($HexString.Length / 2)
For($i=0; $i -lt $HexString.Length; $i+=2){
$Bytes[$i/2] = [convert]::ToByte($HexString.Substring($i, 2), 16)
}
$Bytes
}
After using the function the hex is converted to a byte array such as this:
I need to take the unsigned byte array and convert o to 8bit signed byte array, like the one below:
Is this possible? If so how can it be implemented?
I've tried using the BitConverter class but, as far as I saw, it can only convert to int16.
Thanks in advance
回答1:
To get a [byte[]]
array ([byte]
== System.Byte, an unsigned 8-bit integer type):
$hexStr = 'A591BF86E5D7D9837EE7ACC569C4B59B' # sample input
[byte[]] ($hexStr -split '(.{2})' -ne '' -replace '^', '0X')
-split '(.{2})'
splits the input string by 2-character sequences, and enclosure in(...)
causes these sequences to be included in the returned tokens;-ne ''
then weeds out the empty tokens (which are technically the actual data tokens).-replace , '^', '0X'
places prefix0X
before each resulting 2-hex-digit string, yielding array'0XA5', '0X91', ...
casting the result to
[byte[]]
helpfully recognizes this hex format directly.- Note: If you forget the cast, you'll get an array of strings.
To get an [sbyte[]]
array ([sbyte]
== System.SByte, a signed 8-bit integer), cast directly to [sbyte[]]
instead; do not try to combine the casts: )[sbyte[]] [byte[]] (...)
If you're given a [byte[]]
array that you then want to convert to [sbyte[]]
, use the following (there may be more efficient approaches):
[byte[]] $bytes = 0x41, 0xFF # sample input; decimal: 65, 255
# -> [sbyte] values of: 65, -1
[sbyte[]] $sBytes = ($bytes.ForEach('ToString', 'X') -replace '^', '0X')
Applied to your sample values, in decimal notation:
# Input array of [byte]s.
[byte[]] $bytes = 43, 240, 82, 109, 185, 46, 111, 8, 164, 74, 164, 172
# Convert to an [sbyte] array.
[sbyte[]] $sBytes = ($bytes.ForEach('ToString', 'X') -replace '^', '0X')
$sBytes # Output (each signed byte prints on its own line, in decimal form).
Output:
43
-16
82
109
-71
46
111
8
-92
74
-92
-84
来源:https://stackoverflow.com/questions/60065244/is-it-possible-to-convert-a-byte-array-to-a-8-bit-signed-integer-array-in-powers