diff --git a/protocols/bgp/packet/path_attributes.go b/protocols/bgp/packet/path_attributes.go
index 819fc7b945d858fa30c4a34119c1c98a914dadab..3f2f48e089ba6614b0a06234eb1cc3e4875e5ff5 100644
--- a/protocols/bgp/packet/path_attributes.go
+++ b/protocols/bgp/packet/path_attributes.go
@@ -499,17 +499,17 @@ func (pa *PathAttribute) serializeASPath(buf *bytes.Buffer, opt *EncodeOptions)
 	buf.WriteByte(attrFlags)
 	buf.WriteByte(ASPathAttr)
 
+	asnLength := uint8(2)
+	if opt.Use32BitASN {
+		asnLength = 4
+	}
+
 	length := uint8(0)
 	segmentsBuf := bytes.NewBuffer(nil)
 	for _, segment := range pa.Value.(types.ASPath) {
 		segmentsBuf.WriteByte(segment.Type)
 		segmentsBuf.WriteByte(uint8(len(segment.ASNs)))
 
-		asnLength := uint8(2)
-		if opt.Use32BitASN {
-			asnLength = 4
-		}
-
 		for _, asn := range segment.ASNs {
 			if opt.Use32BitASN {
 				segmentsBuf.Write(convert.Uint32Byte(asn))