为了得到一个[byte[]]
array ([byte]
== System.Byte, an unsigned8 位整数类型):
$hexStr = 'A591BF86E5D7D9837EE7ACC569C4B59B' # sample input
[byte[]] -split ($hexStr -replace '..', '0x$& ')
-
-replace , '..', '0x& '
插入物0x
在每对之前(..
) 的十六进制数字,然后插入一个空格,产生字符串'0xA5 0x91 ... '
-
-split
应用于结果字符串,按空格将字符串拆分为array各个字节表示的数量('0xA5', '0x91', ...
)
-
将结果投射到[byte[]]
有助于直接识别这种十六进制格式。
- 注意:如果你忘记了演员表,你会得到一个数组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[]] (...)
)
更简单的 PowerShell(核心)7.1+选择,使用.NET 5+[System.Convert]::FromHexString() method:
$hexStr = 'A591BF86E5D7D9837EE7ACC569C4B59B' # sample input
# Directly returns a [byte[]] array.
# Cast to [sbyte[]] if you need [sbyte] instances.
[System.Convert]::FromHexString($hexStr)
如果你是given a [byte[]]
数组你then想要转换为[sbyte[]]
,使用以下方法(可能有更有效的方法):
[byte[]] $bytes = 0x41, 0xFF # sample input; decimal: 65, 255
# -> [sbyte] values of: 65, -1
[sbyte[]] $sBytes = $bytes.ForEach('ToString', 'x') -replace '^', '0x'
应用于您的样本值,以十进制表示:
# 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