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

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class Program
{
    public static List<byte> RemoveTrailingNulls(List<byte> byteList) {
        while (byteList.Count > 0 && byteList[byteList.Count - 1] == 0) {
            byteList.RemoveAt(byteList.Count - 1);
        }
        
        return byteList;
    }

    public static void Main()
    {
        List<byte> byteList = new List<byte> { 1, 2, 3, 0, 0, 0, 0 };

        List<byte> trimmedList = RemoveTrailingNulls(byteList);

        foreach (byte b in trimmedList) {
            Console.Write(b + " ");
        }
    }
}



/*
run:

1 2 3 

*/

 



answered Mar 13, 2025 by avibootz

Related questions

2 answers 139 views
1 answer 107 views
1 answer 146 views
1 answer 105 views
2 answers 107 views
1 answer 93 views
1 answer 87 views
...