Bitwise endian swap for various types
Asked Answered
S

5

12

With the help of various sources, I have written some SwapBytes methods in my binary reader class that swap endian in ushort, uint, and ulong, all using bitwise operations all in raw C# with no need for any unsafe code.

public ushort SwapBytes(ushort x)
{
    return (ushort)((ushort)((x & 0xff) << 8) | ((x >> 8) & 0xff));
}

public uint SwapBytes(uint x)
{
    return ((x & 0x000000ff) << 24) +
           ((x & 0x0000ff00) << 8) +
           ((x & 0x00ff0000) >> 8) +
           ((x & 0xff000000) >> 24);
}

public ulong SwapBytes(ulong value)
{
    ulong uvalue = value;
    ulong swapped =
         ((0x00000000000000FF) & (uvalue >> 56)
         | (0x000000000000FF00) & (uvalue >> 40)
         | (0x0000000000FF0000) & (uvalue >> 24)
         | (0x00000000FF000000) & (uvalue >> 8)
         | (0x000000FF00000000) & (uvalue << 8)
         | (0x0000FF0000000000) & (uvalue << 24)
         | (0x00FF000000000000) & (uvalue << 40)
         | (0xFF00000000000000) & (uvalue << 56));
    return swapped;
}

How would i go about creating the same methods but for the signed versions of each of these types, such as short, int and long, Using only the same methods as above, and what improvements could be made to the methods above?

Shipload answered 24/10, 2013 at 8:10 Comment(3)
Why do you need to swap in the first place? Couldn't you directly read using desired endianness from the input byte array? In my experience that leads to faster, easier to read and easier to test code.Familial
Nowadays there is BinaryPrimitives.ReverseEndianness.Roebuck
@Roebuck this new standard way. Maybe add this as an answerMarkettamarkey
Y
24

Instead of conceptually deconstructing to separate bytes and then reassembling them the other way around, you can conceptually swap groups of bytes, like this: (not tested)

public uint SwapBytes(uint x)
{
    // swap adjacent 16-bit blocks
    x = (x >> 16) | (x << 16);
    // swap adjacent 8-bit blocks
    return ((x & 0xFF00FF00) >> 8) | ((x & 0x00FF00FF) << 8);
}

Doesn't help much (or at all) for 32 bits, but for 64 bits it does (not tested)

public ulong SwapBytes(ulong x)
{
    // swap adjacent 32-bit blocks
    x = (x >> 32) | (x << 32);
    // swap adjacent 16-bit blocks
    x = ((x & 0xFFFF0000FFFF0000) >> 16) | ((x & 0x0000FFFF0000FFFF) << 16);
    // swap adjacent 8-bit blocks
    return ((x & 0xFF00FF00FF00FF00) >> 8) | ((x & 0x00FF00FF00FF00FF) << 8);
}

For signed types, just cast to unsigned, do this, then cast back.

Yearling answered 24/10, 2013 at 8:19 Comment(1)
And please keep the comments. I know I'd be quite puzzled before figuring out what those bitmasks and shifting around was good for!Hallie
O
11

You should have a look to following msdn page : http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx

You may simply use Array.Reverse and bitConverter:

  int value = 12345678;
  byte[] bytes = BitConverter.GetBytes(value);

  Array.Reverse(bytes); 
  int result = BitConverter.ToInt32(bytes, 0);
Ona answered 24/10, 2013 at 8:15 Comment(4)
As i said, i would like to use bitwise operators rather than converting between types and swapping around arraysShipload
This is certainly going to be much slower than the code the OP has given. You can benchmark it and see.Cynthea
BitConverter uses native endianness, is slow and the Array.Reverse spams an unnecessary instance making it even slower.Familial
Fine. I don't realy want to benchmark it. I believe you. It's just a short (and easily maintainable) way to write it in case performance is not an issue.Ona
R
5

For the sake of completeness -- nowadays there is BinaryPrimitives.ReverseEndianness.

Roebuck answered 10/11, 2022 at 20:32 Comment(0)
F
2

Just add a cast to unsigned at the start and back to signed at the end.

public long SwapBytes(long value)
{
    return (long)SwapBytes((ulong)value);
}

It might be necessary to manually inline the call to SwapBytes for maximal performance.


On a different note, you might want to avoid swapping, in favour of directly reading the data from the original byte array in the desired endianness. See Efficient way to read big endian data in C# for details.

Familial answered 24/10, 2013 at 8:18 Comment(0)
F
-2

This is probably the easiest and lazy way to replace bits in an integer:

using System;

namespace BitSwap
{
  class Program    
  {
    static void Main()        
    {
        //swaps bits {p, p+1, …, p+k-1} with bits {q, q+1, …, q+k-1} of n.
        Console.WriteLine("n=");
        uint n = uint.Parse(Console.ReadLine());
        Console.WriteLine("p=");
        int p = int.Parse(Console.ReadLine());
        Console.WriteLine("q=");
        int q = int.Parse(Console.ReadLine());
        Console.WriteLine("k=");
        int k = int.Parse(Console.ReadLine());
        int i;
        int s;
        if ((p + k - 1) < 32 && (q + k - 1) < 32 && p > 0 && q > 0)
        // for integer
        {
            for (i = p, s = q; i <= p + k - 1 && s <= q + k - 1; i++, s++)
            {
                uint firstBits = (n >> i) & 1;
                uint secondBits = (n >> s) & 1;
                uint maskFirstBits = (uint)1 << i;
                uint maskSecondBits = (uint)1 << s;
                n = (n & ~maskFirstBits) | (secondBits << i);
                n = (n & ~maskSecondBits) | (firstBits << s);
            }
            Console.WriteLine("Result: {0}", n);
        }
        else
        {
            Console.WriteLine("Invalid entry.");
        }
     }
   }
 }
Fathead answered 13/8, 2017 at 19:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.