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

1 Answer

0 votes
package main

import (
	"fmt"
)

func removeTrailingNulls(data []byte) []byte {
	// Find the position of the last non-null byte
	lastNonNull := len(data) - 1
	
	for lastNonNull >= 0 && data[lastNonNull] == 0 {
		lastNonNull--
	}
	
	// Slice the array up to the last non-null byte
	return data[:lastNonNull + 1]
}

func main() {
	data := []byte{1, 2, 3, 0, 0, 0, 0}
	
	trimmedData := removeTrailingNulls(data)
	
	fmt.Println(trimmedData) 
}



/*
run:

[1 2 3]

*/

 



answered Mar 12, 2025 by avibootz

Related questions

1 answer 146 views
1 answer 105 views
2 answers 107 views
1 answer 87 views
1 answer 159 views
2 answers 110 views
4 answers 136 views
...