SoFunction
Updated on 2025-03-07

C# uses byte array Byte[] to operate primitive type data

1. : Calculate how many bytes are composed of an array of primitive types.

The result of this method is equal to "primitive type byte length * array length"

var bytes = new byte[] { 1, 2, 3 };
var shorts = new short[] { 1, 2, 3 };
var ints = new int[] { 1, 2, 3 };
((bytes)); // 1 byte * 3 elements = 3
((shorts)); // 2 byte * 3 elements = 6
((ints)); // 4 byte * 3 elements = 12

2.: Get the value at the specified index of the byte in the array memory.

public static byte GetByte(Array array, int index)

var ints = new int[] { 0x04030201, 0x0d0c0b0a };
var b = (ints, 2); // 0x03

Analysis:

(1) First combine the array into a "big integer" according to the element index number size as high and low bits.
Combination result: 0d0c0b0a 04030201
(2) index represents the byte number starting from the low bit. The right starts with 0, and index 2 is naturally 0x03.

3.: Set the value at the specified index of the array memory bytes.

public static void SetByte(Array array, int index, byte value)

var ints = new int[] { 0x04030201, 0x0d0c0b0a };
(ints, 2, 0xff);

Before operation: 0d0c0b0a 04030201
After operation: 0d0c0b0a 04ff0201

Result : new int[] { 0x04ff0201, 0x0d0c0b0a };

4.: Copy the specified number of bytes from the source array starting at a specific offset to the target array starting at a specific offset.

public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count)

  • src: Source buffer.
  • srcOffset: byte offset of src.
  • dst: target buffer.
  • dstOffset: byte offset of dst.
  • count: The number of bytes to be copied.

Example 1: The values ​​of bytes 0-16 in the arr array are copied to bytes 12-28: (int accounts for 4 bytes bytes)

int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
(arr, 0 * 4, arr, 3 * 4, 4 * 4);
foreach (var e in arr)
{
     (e);//2,4,6,2,4,6,8,16,18,20
}

Example 2:

var bytes = new byte[] { 0x0a, 0x0b, 0x0c, 0x0d};
var ints = new int[] { 0x00000001, 0x00000002 };
(bytes, 1, ints, 2, 2);

bytes combination result: 0d 0c 0b 0a
ints combination result: 00000002 00000001
(1) Start to extract 2 bytes from the src position 1, from the left, then it should be "0c 0b".
(2) Write dst position 2, then the result should be "00000002 0c0b0001".
(3) ints = { 0x0c0b0001, 0x0000002 }, which conforms to the program running results.

This is what this article about C#’s use of Byte array Byte[] to operate primitive type data. I hope it will be helpful to everyone's learning and I hope everyone will support me more.