我如何有效地填充字节数组 [英] How do I left pad a byte array efficiently

查看:54
本文介绍了我如何有效地填充字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组

LogoDataBy
{byte[0x00000008]}
    [0x00000000]: 0x41
    [0x00000001]: 0x42
    [0x00000002]: 0x43
    [0x00000003]: 0x44
    [0x00000004]: 0x31
    [0x00000005]: 0x32
    [0x00000006]: 0x33
    [0x00000007]: 0x34

我想创建一个任意长度的数组,并用 0x00

I would like to create an array of an arbitrary length and left pad it with 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

我在这里有我的当前片段

I have my current snippet here

        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];
        }

有没有更有效的方法?

推荐答案

我建议从 Array.Copy 开始,如下所示:

I would recommend starting with Array.Copy like this:

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);

如果您确实需要速度,也可以执行 Buffer.BlockCopy :

If you really need the speed you can do Buffer.BlockCopy too:

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);

请注意,我没有检查您提供的数组的长度-您应注意其足够大.

Note that I did not check the length of the array you provided - you should take care that it's big enough.

这篇关于我如何有效地填充字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆