繁体   English   中英

是否可以在 Powershell 中将字节数组转换为 8 位有符号整数数组?

[英]Is it possible to convert a byte array to a 8-bit signed integer array in Powershell?

我正在尝试在 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  
}

使用该函数后,十六进制转换为字节数组,如下所示:

无符号字节数组

我需要采用无符号字节数组并将 o 转换为 8 位有符号字节数组,如下所示:

有符号的 8 位整数数组(字节数组)

这可能吗? 如果可以,如何实施?

我试过使用 BitConverter 类,但据我所知,它只能转换为 int16。

提前致谢

要获取[byte[]]数组[byte] == System.Byte ,一种无符号8 位整数类型):

$hexStr = 'A591BF86E5D7D9837EE7ACC569C4B59B' # sample input

[byte[]] ($hexStr -split '(.{2})' -ne '' -replace '^', '0X')
  • -split '(.{2})'将输入字符串拆分为 2 个字符的序列,并且(...)封闭使这些序列包含在返回的标记中; -ne ''然后清除标记(技术上是实际的数据标记)。

  • -replace , '^', '0X'在每个生成的 2 位十六进制数字字符串之前放置前缀0X ,生成数组'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')

应用于您的样本值,以十进制表示法:

# 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).

输出:

43
-16
82
109
-71
46
111
8
-92
74
-92
-84

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM