开发者

Converting a byte swapping/shifting code snippet from C++ to .NET

开发者 https://www.devze.com 2023-01-11 19:13 出处:网络
I have a short code snippet in C++ and I need to have the same functionality in C#: typedef enum {eD=0x0, eV=0x1, eVO=0x2, eVC=0x3} eIM;

I have a short code snippet in C++ and I need to have the same functionality in C#:

typedef enum {eD=0x0, eV=0x1, eVO=0x2, eVC=0x3} eIM;
#define htonl(x)  ( ( ( ( x ) & 0x000000ff ) << 24 ) | \
                    ( ( ( x ) & 0x0000ff00 ) << 8  ) | \
                    ( ( ( x ) & 0x00ff0000 ) >> 8  ) | \
                    ( ( ( x ) & 0xff0000开发者_运维百科00 ) >> 24 ) )

int value = htonl(eV);

Unfortunately I'm no big programmer, so I need some help.


enum eIM { eD = 0, eV, eVO, eVC }
int value = System.Net.IPAddress.HostToNetworkOrder((int)eIM.eV);


Well, remember that C# is managed code, so you shouldn't try to do bit manipulation too much with it. And, C# complained that I needed to use unsigned integers in my code, but try:

uint htonl(uint i)
{
    return (((i & 0x000000ff) << 24) | ((i & 0x0000ff00) << 8) | ((i & 0x00ff0000) >> 8) | ((i & 0xff000000) >> 24));
}


public enum eIM {eD=0x0, eV=0x1, eVO=0x2, eVC=0x3}

public static class ByteReverser
{
    public static uint ReverseBytes(uint value)
    {
        return (uint)((uint)((value & 0x000000ff) << 24) |
                      (uint)((value & 0x0000ff00) << 8) |
                      (uint)((value & 0x00ff0000) >> 8) |
                      (uint)((value & 0xff000000) >> 24));
    }
}

And, later:

var value = ByteReverser.ReverseBytes((uint)eIM.eV);
0

精彩评论

暂无评论...
验证码 换一张
取 消