Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,023 questions

51,974 answers

573 users

How to remove trailing nulls (0) from byte array in C#

2 Answers

0 votes
using System;

class Program
{
    static void Main()
    {
        byte[] byteArray = { 1, 2, 3, 0, 0, 0, 0 };
        int lastNonNullIndex = Array.FindLastIndex(byteArray, b => b != 0);

        // Create a new array with trimmed elements
        byte[] trimmedArray = new byte[lastNonNullIndex + 1];
        Array.Copy(byteArray, trimmedArray, trimmedArray.Length);

        foreach (var b in trimmedArray) {
            Console.Write(b + " ");
        }
    }
}


/*
run:

1 2 3 

*/

 



answered Mar 12, 2025 by avibootz
0 votes
using System;

public class Program
{
    public static void Main()
    {
        byte[] byteArray = { 1, 2, 3, 0, 0, 0, 0 };
        byte[] trimmedArray = RemoveTrailingNulls(byteArray);
        
        Console.WriteLine(string.Join(", ", trimmedArray)); // Output: 1, 2, 3
    }

    public static byte[] RemoveTrailingNulls(byte[] byteArray)   {
        if (byteArray == null || byteArray.Length == 0)
            return byteArray;

        int newLength = byteArray.Length;
        while (newLength > 0 && byteArray[newLength - 1] == 0)  {
            newLength--;
        }
        
        byte[] trimmedArray = new byte[newLength];
        Array.Copy(byteArray, trimmedArray, newLength);

        return trimmedArray;
    }
}


/*
run:

1, 2, 3

*/

 



answered Mar 12, 2025 by avibootz

Related questions

1 answer 82 views
1 answer 113 views
1 answer 95 views
2 answers 90 views
1 answer 75 views
1 answer 126 views
1 answer 74 views
...