Nul*_*nce 5 .net c# bytearray padding
假设我有一个数组
LogoDataBy
{byte[0x00000008]}
[0x00000000]: 0x41
[0x00000001]: 0x42
[0x00000002]: 0x43
[0x00000003]: 0x44
[0x00000004]: 0x31
[0x00000005]: 0x32
[0x00000006]: 0x33
[0x00000007]: 0x34
Run Code Online (Sandbox Code Playgroud)
我想创建一个任意长度的数组,并将其填充 0x00
newArray
{byte[0x00000010]}
[0x00000000]: 0x00
[0x00000001]: 0x00
[0x00000002]: 0x00
[0x00000003]: 0x00
[0x00000004]: 0x00
[0x00000005]: 0x00
[0x00000006]: 0x00
[0x00000007]: 0x00
[0x00000008]: 0x41
[0x00000009]: 0x42
[0x0000000a]: 0x43
[0x0000000b]: 0x44
[0x0000000c]: 0x31
[0x0000000d]: 0x32
[0x0000000e]: 0x33
[0x0000000f]: 0x34
Run Code Online (Sandbox Code Playgroud)
我这里有我现在的片段
string test = "ABCD1234";
byte[] LogoDataBy = ASCIIEncoding.ASCII.GetBytes(test);
var newArray = new byte[16];
var difference = newArray.Length - LogoDataBy.Length;
for (int i = 0; i < LogoDataBy.Length; i++)
{
newArray[difference + i] = LogoDataBy[i];
}
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来做到这一点?
Car*_*ten 10
我建议从Array.Copy这样开始:
string test = "ABCD1234";
byte[] LogoDataBy = ASCIIEncoding.ASCII.GetBytes(test);
var newArray = new byte[16];
var startAt = newArray.Length - LogoDataBy.Length;
Array.Copy(LogoDataBy, 0, newArray, startAt, LogoDataBy.Length);
Run Code Online (Sandbox Code Playgroud)
如果你真的需要速度,你也可以这样做Buffer.BlockCopy:
string test = "ABCD1234";
byte[] LogoDataBy = ASCIIEncoding.ASCII.GetBytes(test);
var newArray = new byte[16];
var startAt = newArray.Length - LogoDataBy.Length;
Buffer.BlockCopy(LogoDataBy, 0, newArray, startAt, LogoDataBy.Length);
Run Code Online (Sandbox Code Playgroud)
请注意,我没有检查您提供的阵列的长度 - 您应该注意它足够大.
根据您如何定义“更高效”,这可能是值得做的:
var newArray =
Enumerable
.Repeat<Byte>(0, 16 - LogoDataBy.Length)
.Concat(LogoDataBy)
.ToArray();
Run Code Online (Sandbox Code Playgroud)
这在计算上可能不是更有效,但在使代码清晰和可维护方面,您可能会认为这是一种有效的编码方式。
| 归档时间: |
|
| 查看次数: |
6468 次 |
| 最近记录: |