用其他数组替换部分数组的最简单方法? (将二进制数据修补到文件中)
Simplest way to replace part of array with other array? (patching binary data into file)
用 PS 将二进制数据块修补到一个文件中,这是我想出的最好的方法(为简洁起见,所有内容都进行了硬编码):
$bytes = [IO.File]::ReadAllBytes("FILE.DAT")
for ($i = 0; $i -lt 7; $i++) {
$bytes[73 + $i] = (0xCD, 0xCD, 0xCD, 0xA7, 0x91, 0xAB, 0xD2)[$i]
}
[IO.File]::WriteAllBytes("FILE.DAT", $bytes)
它可以工作,但是没有更简单的方法可以在数组上执行此类操作,例如仅使用一个运算符或调用而不使用 for
循环来一次替换一个元素(此处:字节)?
有了 PowerShell 中的所有高级好东西,我希望会有类似 -replace
op 的版本,或 C 中的 memcpy()
,或技巧 $b = $a | foreach {$_}
强制通过 val 而不是通过 ref 数组赋值,或者可能是这个(失败):
$bytes[73..79] = 0xCD, 0xCD, 0xCD, 0xA7, 0x91, 0xAB, 0xD2 # "Array assignment ... failed because assignment to slices is not supported"
另一方面,我注意到 @()
数组运算符经常用于此类示例中,尽管这不是必需的。对此有争论吗?
您可以使用 Array.CopyTo
方法:
Copies all the elements of the current one-dimensional array to the specified one-dimensional array starting at the specified destination array index.
([byte[]](0xCD, 0xCD, 0xCD, 0xA7, 0x91, 0xAB, 0xD2)).CopyTo($bytes,73)
用 PS 将二进制数据块修补到一个文件中,这是我想出的最好的方法(为简洁起见,所有内容都进行了硬编码):
$bytes = [IO.File]::ReadAllBytes("FILE.DAT")
for ($i = 0; $i -lt 7; $i++) {
$bytes[73 + $i] = (0xCD, 0xCD, 0xCD, 0xA7, 0x91, 0xAB, 0xD2)[$i]
}
[IO.File]::WriteAllBytes("FILE.DAT", $bytes)
它可以工作,但是没有更简单的方法可以在数组上执行此类操作,例如仅使用一个运算符或调用而不使用 for
循环来一次替换一个元素(此处:字节)?
有了 PowerShell 中的所有高级好东西,我希望会有类似 -replace
op 的版本,或 C 中的 memcpy()
,或技巧 $b = $a | foreach {$_}
强制通过 val 而不是通过 ref 数组赋值,或者可能是这个(失败):
$bytes[73..79] = 0xCD, 0xCD, 0xCD, 0xA7, 0x91, 0xAB, 0xD2 # "Array assignment ... failed because assignment to slices is not supported"
另一方面,我注意到 @()
数组运算符经常用于此类示例中,尽管这不是必需的。对此有争论吗?
您可以使用 Array.CopyTo
方法:
Copies all the elements of the current one-dimensional array to the specified one-dimensional array starting at the specified destination array index.
([byte[]](0xCD, 0xCD, 0xCD, 0xA7, 0x91, 0xAB, 0xD2)).CopyTo($bytes,73)