raf*_*000 2 arrays powershell signed type-conversion
我正在尝试在 Powershell 中将十六进制字符串转换为 8 位有符号整数数组。
我使用以下函数将十六进制字符串(例如 A591BF86E5D7D9837EE7ACC569C4B59B)转换为字节数组,然后我需要将其转换为 8 位有符号整数数组。
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
}
Run Code Online (Sandbox Code Playgroud)
使用该函数后,十六进制转换为字节数组,如下所示:
我需要采用无符号字节数组并将 o 转换为 8 位有符号字节数组,如下所示:
这可能吗?如果可以,如何实施?
我试过使用 BitConverter 类,但据我所知,它只能转换为 int16。
提前致谢
要获取[byte[]]数组([byte]== System.Byte,无符号8 位整数类型):
$hexStr = 'A591BF86E5D7D9837EE7ACC569C4B59B' # sample input
[byte[]] ($hexStr -split '(.{2})' -ne '' -replace '^', '0X')
Run Code Online (Sandbox Code Playgroud)
-split '(.{2})'将输入字符串拆分为 2 个字符的序列,并将(...)这些序列包含在返回的标记中;-ne ''然后清除空令牌(从技术上讲,它们是实际的数据令牌)。
-replace , '^', '0X'0X在每个生成的 2 进制数字字符串之前放置前缀,产生数组'0XA5', '0X91', ...
将结果转换为[byte[]]有助于直接识别此十六进制格式。
为了得到一个[sbyte[]]阵列([sbyte]== System.SByte,一个签名的8位整数),投直接到[sbyte[]]代替; 千万不能尝试结合的石膏:)[sbyte[]] [byte[]] (...)
如果您得到一个[byte[]]数组,然后您想将其转换为[sbyte[]],请使用以下方法(可能有更有效的方法):
[byte[]] $bytes = 0x41, 0xFF # sample input; decimal: 65, 255
# -> [sbyte] values of: 65, -1
[sbyte[]] $sBytes = ($bytes.ForEach('ToString', 'X') -replace '^', '0X')
Run Code Online (Sandbox Code Playgroud)
应用于您的样本值,以十进制表示法:
# 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).
Run Code Online (Sandbox Code Playgroud)
输出:
[byte[]] $bytes = 0x41, 0xFF # sample input; decimal: 65, 255
# -> [sbyte] values of: 65, -1
[sbyte[]] $sBytes = ($bytes.ForEach('ToString', 'X') -replace '^', '0X')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
681 次 |
| 最近记录: |