c# how to add byte to byte array

前端 未结 6 623
梦毁少年i
梦毁少年i 2020-12-08 15:30

How to add a byte to the beginning of an existing byte array? My goal is to make array what\'s 3 bytes long to 4 bytes. So that\'s why I need to add 00 padding in the beginn

6条回答
  •  一向
    一向 (楼主)
    2020-12-08 16:12

    As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:

    var mahByteArray = new ArrayList();
    

    If you have a byte array from elsewhere, you can use the AddRange function.

    mahByteArray.AddRange(mahOldByteArray);
    

    Then you can use Add() and Insert() to add elements.

    mahByteArray.Add(0x00); // Adds 0x00 to the end.
    mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.
    

    Need it back in an array? .ToArray() has you covered!

    mahOldByteArray = mahByteArray.ToArray();
    

提交回复
热议问题