tags:

views:

47

answers:

3

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 ) & 0xff000000 ) >> 24 ) )

int value = htonl(eV);

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

+5  A: 
enum eIM { eD = 0, eV, eVO, eVC }
int value = System.Net.IPAddress.HostToNetworkOrder((int)eIM.eV);
Mark H
Thanks, I will try that tomorrow.Are the other enums numbered automatically?
asdrubael
@asdrubael - yes, in both C# and C++. The = 0 isn't necessary either as it is default, but it can help for readability to have the numbers there if you want em.
Mark H
A: 

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));
}
palswim
A: 
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);
kbrimington