You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中如何将String System Object转换为Byte[] System Array?

如何将字符串转换为Byte[]数组?

我希望从二进制字符串创建二进制Blob,就像用.NET文件流从文件读取二进制Blob到缓冲区的方式一样,之后从Blob的特定偏移量读取2字节。

失败的直接字符串操作

尝试直接用字符串调用BitConverter时执行失败:

echo "AAAABBBB" > .\zzblob.txt 
$bytes = "AAAABBBB`r`n"
$aa = [system.bitconverter]::touint16($bytes, 0)

# 执行失败!

# 检查变量类型:
$bytes.GetType() | select Name, BaseType | ft -HideTableHeaders

# 输出:String System.Object

成功的文件流读取方式

通过文件流读取到字节缓冲区的方式可以正常完成需求:

$fp = ".\zzblob.txt"
$bf = (new-object byte[](256))
$sp = New-Object System.IO.FileStream($fp, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
$sp.Length
$sp.Read($bf, 0, 256)
$sp.close()

$aa = [system.bitconverter]::touint16($bf, 2)   # ..AA
d2h $aa
# 输出:0x4141  ## 执行成功!

# 检查变量类型:
$bf.GetType() | select Name, BaseType | ft -HideTableHeaders

# 输出:Byte[] System.Array

解决方案:字符串转Byte[]

要将String类型转换为Byte[]类型,需要借助.NET的编码类进行转换,根据字符编码需求选择对应方法:

方法1:ASCII编码转换

$str = "AAAABBBB`r`n"
$byteArray = [System.Text.Encoding]::ASCII.GetBytes($str)
# 此时$byteArray为Byte[]类型
$aa = [System.BitConverter]::ToUInt16($byteArray, 0)
d2h $aa
# 输出:0x4141

方法2:UTF-8编码转换(通用默认选择)

$str = "AAAABBBB`r`n"
$byteArray = [System.Text.Encoding]::UTF8.GetBytes($str)
$aa = [System.BitConverter]::ToUInt16($byteArray, 0)
d2h $aa
# 输出:0x4141

注意:如果字符串包含非ASCII字符,不同编码生成的字节数组会有差异,请根据实际场景选择匹配的编码格式。


内容的提问来源于stack exchange,提问作者not2qubit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 04:41:15