@@ -128,21 +128,54 @@ public static string HexStr(this byte[] buffer, char? separator = null)
128128
129129 public static string HexStr ( this byte [ ] buffer , int length , char ? separator = null )
130130 {
131- string rv = string . Empty ;
132-
133- for ( int i = 0 ; i < length ; i ++ )
131+ if ( separator is { } s )
134132 {
135- var val = buffer [ i ] ;
136- rv += hexmap [ val >> 4 ] ;
137- rv += hexmap [ val & 15 ] ;
133+ int numberOfChars = length * 3 - 1 ;
134+ #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
135+ return string . Create ( numberOfChars , ( buffer , length , s ) , PopulateNewStringWithSeparator ) ;
136+ #else
137+ var rv = new char [ numberOfChars ] ;
138+ PopulateNewStringWithSeparator ( rv , ( buffer , length , s ) ) ;
139+ return new string ( rv ) ;
140+ #endif
141+ }
142+ else
143+ {
144+ int numberOfChars = length * 2 ;
145+ #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
146+ return string . Create ( numberOfChars , ( buffer , length ) , PopulateNewStringWithoutSeparator ) ;
147+ #else
148+ var rv = new char [ numberOfChars ] ;
149+ PopulateNewStringWithoutSeparator ( rv , ( buffer , length ) ) ;
150+ return new string ( rv ) ;
151+ #endif
152+ }
138153
139- if ( separator != null && i != length - 1 )
154+ static void PopulateNewStringWithSeparator ( Span < char > chars , ( byte [ ] buffer , int length , char separator ) state )
155+ {
156+ var ( buffer , length , s ) = state ;
157+ for ( int i = 0 , j = 0 ; i < length ; i ++ )
140158 {
141- rv += separator ;
159+ var val = buffer [ i ] ;
160+ chars [ j ++ ] = char . ToUpperInvariant ( hexmap [ val >> 4 ] ) ;
161+ chars [ j ++ ] = char . ToUpperInvariant ( hexmap [ val & 15 ] ) ;
162+ if ( j < chars . Length )
163+ {
164+ chars [ j ++ ] = s ;
165+ }
142166 }
143167 }
144168
145- return rv . ToUpper ( ) ;
169+ static void PopulateNewStringWithoutSeparator ( Span < char > chars , ( byte [ ] buffer , int length ) state )
170+ {
171+ var ( buffer , length ) = state ;
172+ for ( int i = 0 , j = 0 ; i < length ; i ++ )
173+ {
174+ var val = buffer [ i ] ;
175+ chars [ j ++ ] = char . ToUpperInvariant ( hexmap [ val >> 4 ] ) ;
176+ chars [ j ++ ] = char . ToUpperInvariant ( hexmap [ val & 15 ] ) ;
177+ }
178+ }
146179 }
147180
148181 public static byte [ ] ParseHexStr ( string hexStr )
0 commit comments