Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit a801103

Browse files
justinvpjkotas
authored andcommitted
IPAddress: Use BinaryPrimitives.ReverseEndianness (#26329)
1 parent 68bab69 commit a801103

File tree

1 file changed

+4
-22
lines changed

1 file changed

+4
-22
lines changed

src/System.Net.Primitives/src/System/Net/IPAddress.cs

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33
// See the LICENSE file in the project root for more information.
44

5+
using System.Buffers.Binary;
56
using System.Diagnostics;
67
using System.Net.Sockets;
78
using System.Runtime.CompilerServices;
@@ -398,36 +399,17 @@ public bool TryFormat(Span<char> destination, out int charsWritten)
398399

399400
public static long HostToNetworkOrder(long host)
400401
{
401-
#if BIGENDIAN
402-
return host;
403-
#else
404-
ulong value = (ulong)host;
405-
value = (value << 32) | (value >> 32);
406-
value = (value & 0x0000FFFF0000FFFF) << 16 | (value & 0xFFFF0000FFFF0000) >> 16;
407-
value = (value & 0x00FF00FF00FF00FF) << 8 | (value & 0xFF00FF00FF00FF00) >> 8;
408-
return (long)value;
409-
#endif
402+
return BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(host) : host;
410403
}
411404

412405
public static int HostToNetworkOrder(int host)
413406
{
414-
#if BIGENDIAN
415-
return host;
416-
#else
417-
uint value = (uint)host;
418-
value = (value << 16) | (value >> 16);
419-
value = (value & 0x00FF00FF) << 8 | (value & 0xFF00FF00) >> 8;
420-
return (int)value;
421-
#endif
407+
return BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(host) : host;
422408
}
423409

424410
public static short HostToNetworkOrder(short host)
425411
{
426-
#if BIGENDIAN
427-
return host;
428-
#else
429-
return unchecked((short)((((int)host & 0xFF) << 8) | (int)((host >> 8) & 0xFF)));
430-
#endif
412+
return BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(host) : host;
431413
}
432414

433415
public static long NetworkToHostOrder(long network)

0 commit comments

Comments
 (0)